我有这段代码,但是当我运行程序时仍然被阻止。使用此代码,我想检查/取消选中所有项目,并在文本文件installer.ini中选中此项以写入#product=name of checkbox
=> product=name of checkbox
如果在文本文件中取消选中此项,我将product=name of checkbox
替换为#product=name of checkbox
。
private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
{
string installerfilename = path + "installer.ini";
string installertext = File.ReadAllText(installerfilename);
var lin =File.ReadLines(path + "installer.ini").ToArray();
CheckBox cb = sender as CheckBox;
if (cb.Checked)
{
for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
{
this.checkedListBox2.SetItemChecked(i, true);
foreach (var txt in lin)
{
if (txt.Contains("#product="))
{
var name = txt.Split('=')[1];
installertext = installertext.Replace("#product=", "product=" + name);
}
File.WriteAllText(installerfilename, installertext);
}
}
}
else if (!cb.Checked)
{
for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
{
this.checkedListBox2.SetItemChecked(i, false);
foreach (var txt in lin)
{
if (txt.Contains("product="))
{
var name1 = txt.Split('=')[1];
installertext = installertext.Replace("product=", "#product=" + name1);
}
File.WriteAllText(installerfilename, installertext);
}
}
}
}
答案 0 :(得分:2)
我很遗憾地说你的问题和代码不是很清楚但是,经过一段时间的学习后,我想我明白你要实现的目标以及问题所在。
首先,我认为您正在尝试使用checkbox1
检查或取消选中所有项目。检查所有项目后,您希望INI文件中的所有产品都处于活动状态(即删除注释符号(即#))。取消选中所有项目后,您希望所有产品都处于非活动状态(即添加评论标记)。
其次,我假设您的INI文件非常大。因为您要遍历所有行并在每行之后保存INI文件,所以您要多次保存INI文件。这会阻止用户界面,直到所有行都被处理完毕。
解决方案(基于您当前的方法)
private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
{
CheckBox cb = sender as CheckBox;
SetAllItemsChecked(cb.Checked);
var installerLines = ReadInstallerLines();
SetAllProductsChecked(installerLines.ToList(), cb.Checked);
SaveInstaller(installerLines);
}
private void SetAllItemsChecked(bool check)
{
for (int i = 0; i < this.checkedListBox2.Items.Count; i++)
{
this.checkedListBox2.SetItemChecked(i, check);
}
}
private IEnumerable<string> ReadInstallerLines()
{
string installerfilename = path + "installer.ini";
string installertext = File.ReadAllText(installerfilename);
return File.ReadLines(path + "installer.ini");
}
private void SetAllProductsChecked(IList<string> installerLines, bool check)
{
for (var i = 0; i < installerLines.Count; i++)
{
if (installerLines[i].Contains("product="))
{
installerLines[i] = check
? installerLines[i].Replace("#product", "product")
: installerLines[i].Replace("product", "#product");
}
}
}
private void SaveInstaller(IEnumerable<string> installerLines)
{
string installerfilename = path + "installer.ini";
File.WriteAllLines(installerfilename, installerLines);
}
提示
花点时间学习seperation of concerns或single responsibility。您当前的代码在一个地方做得太多(处理UI事件,执行IO和应用业务逻辑)。
答案 1 :(得分:0)
你可以直接连接字符串
var name1 = txt.Split('=')[1];
installertext = "#product=" + name1;