开发者

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 fil开发者_运维技巧estream.

Which would work out best in my scenario? I would appreciate some code snipplets too ..

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.

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.

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.

Have a read around the System.IO.FileStream and its constructor overloads and you can tailor exactly how it behaves to suit your purpose.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜