tags:

views:

128

answers:

2

Possible Duplicate:
How to check For File Lock in C# ?

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?

+2  A: 

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
We should probably recommend using a `using` block, as opposed to explicitly calling `Dispose`.
Steven Sudit
@Steven, Agreed... I didn't want to get into how to call dispose, but yes using is in general the best way.
Mike
@Mike: Understood. Fortunately, Brian was kind enough to provide us with a working example.
Steven Sudit
+3  A: 

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
+1 for recommending a working piece of code.
Callum Rogers