[英]How can I prevent my C# application from opening new windows during context menu?
[英]How to prevent my C# application from opening the same file twice
我需要知道何时不再使用C#打开的文本文件-我的应用程序将文本写入txt文件,有时在尝试再次写入文本时仍将其锁定。 不用担心释放该锁之后,另一个进程或单词可能会抢回该锁。 有没有一种方法可以确定文件是否仍被锁定,并在文件未被锁定时重新尝试写入?
以下是使用using
块读取文件的示例,它将为您关闭文件:
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.
当有连续的using
块时,有些人喜欢省略支撑的外层。 为了清楚起见,我将它们包括在内。 请注意, using
块在幕后使用try-finally
块来确保即使有未捕获的异常,文件也将关闭。 这是一件好事。
另请参阅RAII 。
您可能没有正确处理该文件。 如果处理该文件,则可以立即再次对其进行写入,而不必等待文件可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.