Read / write text file repeatedly / simultaneously

How to read and write in a text file without receiving the exception that "The file is already in use by another application"?

I tried the File.readalltext () and File.Appendalltext () functions. I am just starting with filestream.

What will be best in my scenario? I would appreciate some missing code too ..

thank

+3
source share
2 answers

All this is due to the semantics of locking and sharing that you request when opening a file.

Instead of using a keyboard shortcut, File.ReadAllText()try using System.IO.FileStreamand 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();
}

FileShare.ReadWrite - .

-

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

FileShare.Read - .

System.IO.FileStream , , .

+6

, .

, .

, . FileMon .

+1

Source: https://habr.com/ru/post/1755458/


All Articles