one possible fix for a System.IO.IOException error

During testing of a visual studio 2010 C# console application, I encountered the following error when I was trying to open a file and read its contents into a byte array:

System.IO.IOException: The process cannot access the file ‘[FILEPATH\MYFILE.EXT]’ because it is being used by another process.

Looking back over the code I realized that I had opened a file for reading without using the “Using” block.

If you use the “using” construct, then the file is automatically closed.

In my own particular case I replaced the following line of code:

System.IO.FileStream MyFile = new System.IO.FileStream(fil.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);

MyFile.Read(myFileBytes, 0, (int)MyFile.length);

with a “using” block as follows

using (System.IO.FileStream MyFile = new System.IO.FileStream(fil.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
{

MyFile.Read(myFileBytes, 0, (int)MyFile.length);

 Note in the above code within the using block the read method is used to read the bytes of the file into a variable named myFileBytes. The variable myFileBytes is a byte array and it stores the bytes from position zero to the length of MyFile.