FileStream to save file then immediately unlock in .NET?

aron picture aron · Apr 19, 2010 · Viewed 16.2k times · Source

I have this code that saves a pdf file.

FileStream fs = new FileStream(SaveLocation, FileMode.Create);
fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
fs.Flush();
fs.Close();

It works fine. However sometimes it does not release the lock right away and that causes file locking exceptions with functions run after this one run.

Is there a ideal way to release the file lock right after the fs.Close()

Answer

Darin Dimitrov picture Darin Dimitrov · Apr 19, 2010

Here's the ideal:

using (var fs = new FileStream(SaveLocation, FileMode.Create))
{
    fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
}

which is roughly equivalent to:

FileStream fs =  null;
try
{
    fs = new FileStream(SaveLocation, FileMode.Create);
    fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
}
finally
{
    if (fs != null)
    {
        ((IDisposable)fs).Dispose();
    }
}

the using being more readable.


UPDATE:

@aron, now that I'm thinking

File.WriteAllBytes(SaveLocation, result.DocumentBytes);

looks even prettier to the eye than the ideal :-)