简体   繁体   English

重复/同时读/写文本文件

[英]Reading / Writing text file repeatedly / simultaneously

How do I read and write on a text file without getting the exception that "File is already in use by another app"?? 如何读取和写入文本文件而不会得到“文件已被其他应用程序使用”的异常?

I tried File.readalltext() and File.Appendalltext() functions..I'm just starting out with filestream. 我尝试了File.readalltext()和File.Appendalltext()函数。我刚开始使用filestream。

Which would work out best in my scenario? 在我的场景中哪种效果最好? I would appreciate some code snipplets too .. 我也会感谢一些代码snipplets ..

Thanks 谢谢

This is all to do with the lock and sharing semantics that you request when opening the file. 这与打开文件时请求的锁定和共享语义有关。

Instead of using the shortcut approach of File.ReadAllText() , try looking into using a System.IO.FileStream and a System.IO.StreamReader / System.IO.StreamWriter . 而不是使用File.ReadAllText()的快捷方法,尝试使用System.IO.FileStreamSystem.IO.StreamReader / System.IO.StreamWriter

To open a file: 要打开文件:

using (var fileStream = new FileStream(@"c:\myFile", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var streamReader = new StreamReader(fileStream))
{
  var someText = streamReader.ReadToEnd();
}

Note the FileShare.ReadWrite - this is telling the stream to allow sharing to either other readers or other writers. 注意FileShare.ReadWrite - 这告诉流允许与其他读者或其他作者共享。

For writing try something like 写作尝试类似的东西

using (var fileStream = new FileStream(@"c:\myFile", FileMode.Create, FileAccess.Write, FileShare.Read))
using (var streamWriter = new StreamWriter(fileStream))
{
  streamWriter.WriteLine("some text");
}

Note the FileShare.Read - this is telling the stream to allow sharing to readers only. 注意FileShare.Read - 这告诉流只允许向读者共享。

Have a read around the System.IO.FileStream and its constructor overloads and you can tailor exactly how it behaves to suit your purpose. 阅读System.IO.FileStream及其构造函数重载,您可以准确地定制它的行为以适合您的目的。

You need to make sure the file is not being used by any other application. 您需要确保该文件未被任何其他应用程序使用。

With your own application, you cannot read from a file multiple times without closing the stream between reads. 使用您自己的应用程序,如果不在读取之间关闭流,则无法多次读取文件。

You need to find out why the file is in use - a tool like FileMon can help finding out. 你需要找出原因的文件正在使用-就像一个工具的FileMon可以帮助找出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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