0

I need to read the content of a file and overwrite it while the file is locked. I don't want the file to be unlocked between read and write operations.

using (var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
  using (var reader = new StreamReader(file, Encoding.Unicode))
  using (var writer = new StreamWriter(file, Encoding.Unicode))
  {
    // read
    // calculate new content
    // overwrite - how do I do this???
  }
}

If I use two FileStreams, the file is cleared when instantiating the writer but the file will be briefly unlocked between the reader and writer instantiation.

using (var reader = new StreamReader(new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)))
{
  // read
  // calculate new content
}

using (var writer = new StreamWriter(new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)))
{
  // write
}
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Nicolae Daian
  • 1,065
  • 3
  • 18
  • 39

1 Answers1

3

If you keep open the original FileStream you can do it:

using (var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
   // This overload will leave the underlying stream open
  using (var reader = new StreamReader(file, Encoding.Unicode, true, 4096, true))
  {
      //Read
  }

  file.SetLength(0); //Truncate the file and seek to 0

  using (var writer = new StreamWriter(file, Encoding.Unicode))
  {
        //Write the new data
  }
}
Gusman
  • 14,905
  • 2
  • 34
  • 50
  • This takes a dependency on v4.5 since the ctor with leaveOpen is not available before it. – Tanveer Badar Aug 02 '17 at 17:05
  • Thank you for the quick answer! – Nicolae Daian Aug 02 '17 at 17:05
  • There is no reason to use the new `leaveOpen` parameter to solve this problem. Opening the file as read/write is sufficient. The reader and writer can both be created at the same time, with the underlying stream length set after reading, but before writing. – Peter Duniho Aug 02 '17 at 17:18