繁体   English   中英

在同一FileStream上读取和覆盖

[英]Read and overwrite at the same FileStream

我正在使用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已初始化,因此文件为空。

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

OpenOrCreate只是追加...

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

这也显示了您的方法的主要问题:FileStream仅具有一个Position,而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字符损坏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM