简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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