如何$ P $无法打开同一个文件pvent我的C#应用​​程序 [英] How to prevent my C# application from opening the same file twice

查看:167
本文介绍了如何$ P $无法打开同一个文件pvent我的C#应用​​程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  如何检查文件锁定在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:\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.

有些人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

这篇关于如何$ P $无法打开同一个文件pvent我的C#应用​​程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆