出于某种原因,File.ReadLines 使我正在读取的文件保持锁定状态,并且当我尝试使用 streamWriter 将文本写入其中时,我收到一个错误,表明它正在被另一个进程使用。如果我不先阅读它,写入它就可以了。这是我的代码:
IEnumerable<String> lines;
private void loadCfg()
{
lines = File.ReadLines(Application.StartupPath + @"\server.cfg");
foreach (var line in lines)
{
if (line.Contains("Port"))
{
portTxtBox.Text = extractValue(line);
}
if (line.Contains("Cars"))
{
maxCarsCombo.Text = extractValue(line);
}
if (line.Contains("MaxPlayers"))
{
maxPlayerCombo.Text = extractValue(line);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + @"\server.cfg",false);
sw.WriteLine(lines.ElementAt(0));
sw.Close();
}