如何$ P $无法打开同一个文件pvent我的C#应用​​程序我的、无法打开、文件、程序

由网友(天黑路滑人心杂i)分享简介:可能重复: 如何检查文件锁定在C#? 我需要知道什么时候这些受C#打开一个文本文件是不再使用 - 我的应用程序将文本写入一个txt文件,有时试图再次写入它时,它仍然有它的锁。有没有关注到另一个进程或单词可以获取锁回它被释放之后。有没有一种方法,以确定是否该文件仍然锁定,并重新尝试写如果不上锁?I need t...

可能重复:   如何检查文件锁定在C#?

我需要知道什么时候这些受C#打开一个文本文件是不再使用 - 我的应用程序将文本写入一个txt文件,有时试图再次写入它时,它仍然有它的锁。 有没有关注到另一个进程或单词可以获取锁回它被释放之后。 有没有一种方法,以确定是否该文件仍然锁定,并重新尝试写如果不上锁?

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:pathfilename.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.

有些人preFER省略括号外的水平时,有连续的使用块。我已经包括了他们的清晰度。请注意,使用块使用尝试,终于在幕后块,以确保您的文件将关闭,即使有是未捕获的异常。这是一件好事。

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.

参见 RAII 。

阅读全文

相关推荐

最新文章