[英]Save a state of checkbox to specific line of file C #
我搜索了多个解决方案,并找到了一个特别解决我的问题的解决方案:
我想要完成的是将复选框的状态保存到特定的文件行。 我使用相同的代码来保存openFileDialog中的文件补丁。
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var lines = File.ReadAllLines("patcher.conf");
lines[0] = openFileDialog1.FileName;
File.WriteAllLines("patcher.conf", lines);
}
上面的代码将文件补丁保存在文本文件的第1(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个索引行文件)中的复选框状态的信息,错误说:进程无法访问该文件,因为它正由另一个进程使用。 我做错了什么?
在文件流上,您使用了readwrite
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);
您编写文件的方法存在缺陷。 您正在打开文件并读取所有行,但是对于每一行,您将再次读取所有行并将文件保存在同一循环中。 这可能是您的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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.