Thursday, August 25, 2011

Releasing a file handle

I recently came across a problem, where I had to create a blank file and then do some modifications on it. Accordingly I used the following coding:
After importing the System.IO namespace:

File.Create("test.txt");

and then went on to other code where it adds/modifies the file. But this threw a runtime error like "The file is being used by another process", which was reasonable because the above code while creating the file generates a handle which is still being held.

After a couple of workarounds, I came up with the following piece of code, where all the necessary modifications could be done and then release the handle:

using(FileStream fs = new FileStream("test.txt",FileMode.CreateNew,FileAccess.ReadWrite))
{
//do whatever preferred to the file........

//this releases the handle
fs.Close();
}