I need to know when a text file that's opened by C# is not in use anymore - My app writes text to a txt file and sometimes it will still have a lock on it when trying to write to it again. There is no concern that another process or word may grab the lock back after it is released. Is there a way to determine if the file is still locked and to reattempt the write if its not locked?
Asked
Active
Viewed 1,339 times
0
-
Previously asked here: http://stackoverflow.com/questions/1304/how-to-check-for-file-lock-in-c – David Aug 09 '10 at 20:52
-
1@David: No, I think this is a different issue. Here, the real problem is that they're not disposing. – Steven Sudit Aug 09 '10 at 20:53
-
By the way, you can check which process locks a file with various tools, I use "Unlocker" for this. – Dominik Antal Dec 30 '13 at 14:44
2 Answers
3
Below is an example of reading a file using a using
block, which will close the file for you:
using (FileStream fs = File.OpenRead(@"c:\path\filename.txt")) //Open the file here
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
} //File will close when scope of this brace ends.
Some people prefer to omit the outer level of the braces when there are consecutive using
blocks. I have included them for clarity. Note that a using
block uses a try-finally
block under the covers to ensure that your file will close even if there is an uncaught exception. This is a good thing.
See also RAII.

Brian
- 25,523
- 18
- 82
- 173
2
You are probably not disposing of the file correctly. If you dispose of the file, you will be able to write to it again immediately and not have to wait for the file to be available.

Mike
- 3,462
- 22
- 25
-
2We should probably recommend using a `using` block, as opposed to explicitly calling `Dispose`. – Steven Sudit Aug 09 '10 at 20:54
-
@Steven, Agreed... I didn't want to get into how to call dispose, but yes using is in general the best way. – Mike Aug 09 '10 at 21:03
-
Understood. Fortunately, Brian was kind enough to provide us with a working example. – Steven Sudit Aug 09 '10 at 21:51