[英]Read, delete, and write to file while locking via FileShare FileShare.None?
这可能是以前问过的,所以我先向您道歉。 但是,我觉得这里有很多问题的独特之处,因此我认为没有必要解决这个问题。
我正在尝试使用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()
方法,该方法返回要写入文件的信息字符串。
我会这样做:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.