将复选框的状态保存到文件 C# 的特定行
本文关键字:复选框 状态 存到文件 | 更新日期: 2023-09-27 17:56:20
我已经搜索了多个解决方案,但找不到专门解决我问题的解决方案:
我想完成的是将复选框的状态保存到特定的文件行。我使用相同的代码从openFileDialog保存文件补丁。
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var lines = File.ReadAllLines("patcher.conf");
lines[0] = openFileDialog1.FileName;
File.WriteAllLines("patcher.conf", lines);
}
上面的代码将文件补丁保存在文本文件的第一行(0 索引)中,它可以工作!但是出于某种原因,当我尝试在以下方面做同样的事情时:
private void checkexe_CheckedChanged(object sender, EventArgs e)
{
string line;
System.IO.StreamReader file =
new System.IO.StreamReader("patcher.conf");
while ((line = file.ReadLine()) != null)
{
var lines = File.ReadAllLines("patcher.conf");
lines[1] = checkexe.Checked.ToString();
File.WriteAllLines("patcher.conf", lines);
}
file.Close();
}
并将有关复选框状态的信息保存在第二个(文件的 1 个索引行)中,错误显示:进程无法访问该文件,因为它正由另一个进程使用。我做错了什么?
您编写文件的方法有缺陷。您正在打开文件并读取所有行,但对于每一行,您随后再次读取所有行并将文件保存在同一个循环中。这将是导致process cannot access the file because it is being used by another process
错误的原因。
private void checkexe_CheckedChanged(object sender, EventArgs e)
{
string line;
System.IO.StreamReader file = new System.IO.StreamReader("patcher.conf");
while ((line = file.ReadLine()) != null)
{
var lines = File.ReadAllLines("patcher.conf");
lines[1] = checkexe.Checked.ToString();
File.WriteAllLines("patcher.conf", lines);
}
file.Close();
}
相反,请尝试以下操作:(未经测试,但应该会让您朝着正确的方向前进)
private void checkexe_CheckedChanged(object sender, EventArgs e)
{
var lines = File.ReadAllLines("patcher.conf");
for(var i = 0; i < lines.Length; i++)
{
if (i == 1)
lines[i] = checkexe.Checked.ToString();
}
File.WriteAllLines("patcher.conf", lines);
}
在文件流上,你使用了读写
System.IO.FileStream fs = new System.IO.FileStream(txtFilePath.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.FileShare.ReadWrite);
System.IO.StreamReader sr = new System.IO.StreamReader(fs);