- 1 year ago 100
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];

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download