- 4 months ago 26
C# Question

FileStream in use

If my file stream is in use (every time I try to debug, it hits that first line and says it's in use), how can I force a release? every time it hits this code, I get a message saying something is using it:

FileStream fileStream = File.Open(@"C:\somefile", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[fileStream.Length];


Learn to use using:

using (FileStream fileStream = File.Open(@"C:\somefile", FileMode.Open, FileAccess.Read))

The using construct ensures that the file will be closed when you leave the block even if an exception is thrown.

Your problem might not be here, but somewhere else in your code. You'll have to go through all your code and look for places where you have opened files but not put it inside a using statement.