Home > .Net, .Net 3.0 / 3.5 > Writing File with Non Cache mode in C#

Writing File with Non Cache mode in C#

Normally when we are writing to the File Systems or I/O devices, Windows will cache the request or response to get better performance. This behavior is a good feature, but sometimes we require immediate change. By caching Windows sometimes mislead us. And I don’t think there is a way to avoid this option available in Windows. In my current project I got a chance to explore / work on this, but I need to avoid this caching. ;) I checked various options with File class and Stream class but there was no option available to avoid Caching. Later our VC++ developer gives me some code, which in WIN32 API, which will avoid caching. It was using “CreateFile()” method in Kernal32.dll with FILE_FLAG_NO_BUFFERING option. Then I was able to create same in C# code base on the input using PInvoke. But I have to find a managed code, with that we can write / read stream without caching. Later I found FileStream class, which supporting both synchronous and asynchronous read and write operations. But it also doesn’t have a NonCahce file option. Then I tried FileStream class with FILE_FLAG_NO_BUFFERING option. And it worked :)

const FileOptions FILE_FLAG_NO_BUFFERING = (FileOptions) 0x20000000;

using(FileStream fs = new FileStream("Path",FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1024, FileOptions.WriteThrough | FILE_FLAG_NO_BUFFERING))
{
fs.Write("HelloWorld");
}

This FileStream class also got a nice option, FileOptions.DeleteOnClose, if you are creating a File with this option enabled, it will delete the File after you close the FileStream. This can be used for creating real temporary files.

string TempFile = Path.GetTempFileName();
using(FileStream fs = new FileStream(TempFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1024, FileOptions.DeleteOnClose))
{
fs.Write("HelloWorld");
} //Deletes the File.

I think this FileStream class is available from .Net 2.0 Framework onwards.

Categories: .Net, .Net 3.0 / 3.5 Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.