14 Dezember 2009

Improve performance through using FileAccess.Write

At work I’m implementing a little app that copies video files from cameras to network folders. The size of a video file is usually several hundred megabytes. The target file is written with the standard .NET FileStream class. The strange thing I noticed was that calling Close on the stream took between 15 and 20 seconds. Even if I flushed the stream Close call took ages. I created the stream like this

var output = new FileStream(path, FileMode.Create);

After playing with the available constructor overloads I found a better solution:

var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);

Using this overload, the Close call took only 1 millisecond! That means a performance boost of factor 20000 just by using the right FileAccess Options.

Tip: Always use the “Read” or “Write” if you don’t need “ReadWrite”. This will give you a performance boost on network files.