Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何锁定文件、读取其内容并覆盖它?_C#_Filestream_Streamreader_Streamwriter - Fatal编程技术网

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

C# 如何锁定文件、读取其内容并覆盖它?,c#,filestream,streamreader,streamwriter,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(fil

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

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
s,则在实例化writer时会清除该文件,但在reader和writer实例化之间会短暂解锁该文件

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
}

如果保持打开原始文件流,则可以执行以下操作:

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

如果保持打开原始文件流,则可以执行以下操作:

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

这需要依赖于v4.5,因为带有leaveOpen的ctor在此之前不可用。谢谢您的快速回答!没有理由使用新的
leaveOpen
参数来解决此问题。以读/写方式打开文件就足够了。读卡器和写卡器可以同时创建,基本流长度在读取之后、写入之前设置。这需要依赖于v4.5,因为之前没有带leaveOpen的ctor。感谢您的快速回答!没有理由使用新的
leaveOpen
参数来解决此问题。以读/写方式打开文件就足够了。读卡器和写卡器可以同时创建,基本流长度在读取之后、写入之前设置。