2

Is there a way, in C# on Windows, to write a file and flag it as temporary so that the operating system won't bother physically writing it to disk? The file in question is small, and will be read by another program in the very near future, and deleted and rewritten very soon after that, so that keeping it purely in RAM would make sense.

I'm currently writing the file with File.WriteAllText but could use a different API if necessary.

5
  • 6
    Please, have look at MemoryMappedFile msdn.microsoft.com/en-us/library/… Commented May 29, 2017 at 18:30
  • 1
    "keeping it purely in RAM would make sense" - Why? Have you profiled your application and determined, that this is a bottleneck? Commented May 29, 2017 at 21:12
  • @IInspectable It's actually not so much about speed as it is about noise - the human ear suffices to determine that the hard disk thrashing and the cooling fan spinning up, are the 'bottlenecks' for that. (You need not remind me that everyone should be on SSD by now.) Commented May 30, 2017 at 0:22
  • 1
    If you specify FILE_ATTRIBUTE_TEMPORARY when creating the file, that serves as a strong hint to the file system not to bother writing it to disk. I don't know the best way to do that in C# though. Commented May 30, 2017 at 0:34
  • @HarryJohnston: that's covered here. If only FileOptions had a Temporary = 256 member, you could do this without P/Invoking to CreateFile, but in their wisdom the designers chose not to make this option available. (If you try to fudge it in, the FileStream constructor will complain.) Commented May 30, 2017 at 11:10

1 Answer 1

1

That's simple and could be done without any P/Invoke:

var file = File.Create(path); File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Temporary); 

The FileAttributes.Temporary enum value is the same as FILE_ATTRIBUTE_TEMPORARY constant (0x100):

Specifying the FILE_ATTRIBUTE_TEMPORARY attribute causes file systems to avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Although it does not directly control data caching in the same way as the previously mentioned flags, the FILE_ATTRIBUTE_TEMPORARY attribute does tell the system to hold as much as possible in the system cache without writing and therefore may be of concern for certain applications.

source

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.