这可能是以前问过的,所以我提前道歉。然而,我觉得这里有足够的东西是我的问题所独有的,所以我觉得没有理由提出这个问题。
我正在尝试使用FileStream方法打开一个文件。我需要从外部读/写锁下打开这个文件,这就是我在打开它时使用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只是类对象数组的长度。GetInfoLine()是一个方法,它返回要写入文件的信息字符串。
发布于 2018-03-30 22:48:19
我会这样做:
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);
https://stackoverflow.com/questions/49582262
复制相似问题