【问题标题】:Read and overwrite at the same FileStream在同一个 FileStream 上读取和覆盖
【发布时间】:2017-02-08 11:22:47
【问题描述】:

我正在使用FileStream 来锁定文件,使其不能被其他进程写入并对其进行读写,我正在使用以下方法:

public static void ChangeOrAddLine(string newLine, string oldLine = "")
{
  string filePath = "C:\\test.txt";
  FileMode fm = FileMode.Create;
  //FileMode fm = FileMode.OpenOrCreate;
  using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
  using (StreamReader sr = new StreamReader(fs))
  using (StreamWriter sw = new StreamWriter(fs))
  {
    List<string> lines = sr.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
    bool lineFound = false;
    if (oldLine != "")
      for (int i = 0; i < lines.Count; i++)
        if (lines[i] == oldLine)
        {
          lines[i] = newLine;
          lineFound = true;
          break;
        }
    if (!lineFound)
      lines.Add(newLine);
    sw.Write(string.Join("\r\n", lines));
  }
}

我想用新内容覆盖它,但我找不到正确的FileMode,使用FileMode.OpenOrCreate 只是将新内容附加到旧内容,FileMode.Create 当时删除文件内容, FileStream fm已经初始化,所以文件是空的。

我现在只需要清除旧内容,当我将新内容写入其中时,不会在方法运行期间丢失其上的写锁。

【问题讨论】:

标签: c# filestream


【解决方案1】:

OpenOrCreate 只是追加 ...

因为您不会在阅读后重新定位。

这也显示了您的方法的主要问题:FileStream 只有一个位置,并且 Reader 和 Writer 大量使用缓存。

但是,只要您想替换所有内容并且确实需要该锁定方案:

using (FileStream fs = new FileStream(filePath, 
        FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))    
{    
    using (StreamReader sr = new StreamReader(fs))
    {
       ... // all the reading
    }
    fs.Position = 0; 
    using (StreamWriter sw = new StreamWriter(fs))
    {
        sw.Write(string.Join("\r\n", lines));
    }
    fs.SetLength(fs.Position); // untested, something along this line
}

也许你必须说服 sw 和 sr 让他们的流打开。

但我必须注意,FileShare.Read 标志在这种情况下没有太大意义。读者可能会看到各种不一致的数据,包括撕裂的线条和损坏的 UTF8 字符。

【讨论】:

  • 是否需要做:fs.SetLength(fs.Position); ?它还会在我的文件中写入所有内容而不这样做,并且如果新内容比旧内容长
  • SetLength() 存在,以防新内容(可能)比旧内容短。否则你可以放弃它。
猜你喜欢
  • 1970-01-01
  • 2015-12-15
  • 2019-01-31
  • 2018-02-18
  • 2021-12-07
  • 1970-01-01
  • 2013-11-21
相关资源
最近更新 更多