如何锁定文件,读取其内容并覆盖它?

时间:2017-08-02 16:49:48

标签: c# filestream streamreader streamwriter

我需要读取文件的内容并在文件被锁定时覆盖它。我不希望在读写操作之间解锁文件。

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???
  }
}

如果我使用两个FileStream,则在实例化编写器时会清除该文件,但文件将在读者和编写器实例化之间短暂解锁。

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
}

1 个答案:

答案 0 :(得分:3)

如果您继续打开原始FileStream,则可以执行此操作:

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
  }
}