通过 FileShare FileShare.None 锁定时读取、删除和写入文件?

Read, delete, and write to file while locking via FileShare FileShare.None?

这可能之前有人问过,所以我提前道歉。但是,我觉得这里有足够多的部分是我的问题所独有的,我没有发现它值得这个问题。

我正在尝试使用 FileStream 方法打开文件。我需要在 read/write 外部的锁定下打开此文件,这就是我在打开它时使用 FileShare.None 属性的原因。打开并锁定后,我将文件的内容逐行读取到字符串数组中。我根据需要更新的信息更改其中一行,然后将这些行写回到文件中。

我遇到的问题是写入的行附加在读取的原始行之后。我需要在读入文件后擦除该文件,以便我写回的内容是文件中唯一的内容。

我很困惑,因为我不想关闭 FileStream 并以只写方式重新打开它(这应该会清除文件),因为那样会释放我对文件的锁定。

FileStream fs = new FileStream("trains.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);

string[] lines = new string[trains.Length];

//Loop through all lines in the file
for (int i = 0; i < lines.Length; i++)
{
    lines[i] = sr.ReadLine();

    /*If the ID of the train in the file matches the parameter, then
        set the line to the InfoLine of the train.*/
    if (lines[i][0].ToString() == train.ID().ToString())
    {
        lines[i] = train.GetInfoLine();
    }
}

//Write back the lines to the file
for (int i = 0; i < lines.Length; i++)
{
    sw.WriteLine(lines[i]);
}

sw.Close();
sr.Close();
fs.Close();

在上面的代码中,trains.Length 只是 class 个对象数组的长度。 GetInfoLine()是我有的一种方法,returns一串信息我想写入文件。

我会这样做:

string line = "";
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);

List<string> lines = new List<string>();

while ((line = sr.ReadLine()) != null)
{
    line = "*" + line; //Do your processing
    lines.Add(line);
}

fs.SetLength(0);

foreach (var newline in lines)
{
    sw.WriteLine(newline);
}
sw.Flush();
fs.Close();

查看 fs.SetLength(0);