Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileStream to save file then immediately unlock in .NET?

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()

like image 864
aron Avatar asked Apr 19 '10 20:04

aron


2 Answers

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 :-)

like image 93
Darin Dimitrov Avatar answered Oct 01 '22 10:10

Darin Dimitrov


We have seen this same issue in production with a using() statement wrapping it.

One of the top culprits here is anti-virus software which can sneak in after the file is closed, grab it to check it doesn't contain a virus before releasing it.

But even with all anti-virus software out of the mix, in very high load systems with files stored on network shares we still saw the problem occasionally. A, cough, short Thread.Sleep(), cough, after the close seemed to cure it. If someone has a better solution I'd love to hear it!

like image 22
Ian Mercer Avatar answered Oct 01 '22 08:10

Ian Mercer