简体   繁体   中英

How to prevent my C# application from opening the same file twice

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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM