我正在尝试根据字符串的条件和复选框将文本文件中的行替换为另一行。例如,有2个复选框,如果选中1,则应找到字符串X,替换为A
如果选中复选框2,它会找到字符串X并将其替换为B
我发现您无法单独替换文本文件中的特定行,但您必须重写该文件并排除该行。这让我陷入两难境地,因为我需要更换这条线而不仅仅是删除。我通过研究努力了
DialogResult openFile = openFileDialog1.ShowDialog();
if (openFile == DialogResult.OK)
{
string file = openFileDialog1.FileName;
string content = File.ReadAllText(file);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "New Text Doucment";
sfd.Title = "Save As Text File";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = sfd.FileName;
StreamWriter bw = new StreamWriter(File.Create(path));
bw.WriteLine(content);
bw.Close();
File.WriteAllLines(path, File.ReadAllLines(path).Select(x => string.Format("{0},", x)));
string newContent = File.ReadAllText(path);
newContent = newContent.Remove(newContent.LastIndexOf(","));
File.WriteAllText(path, newContent);
StreamReader reader = new StreamReader(path);
string eachLine = reader.ReadLine();
foreach (char value in newContent)
{
if (eachLine.StartsWith("BRUSH"))
{
if (checkBox1.Checked == true)
{
var oldLines = File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains("BRUSH"));
File.WriteAllLines(path, newLines);
}
else if (checkBox2.Checked == true)
{
var oldLines = File.ReadAllLines(path);
var newLines = oldLines.Where(line => !line.Contains("BRUSH"));
File.WriteAllLines(path, newLines);
}
}
}
}
}
我在做什么:
抓取现有文件,
将内容添加到新文件
在每行末尾添加逗号
删除文件末尾的最后一个逗号。
现在我需要将文件BRUSH
中的字符串替换为)),
,如果选中复选框1,或者将BRUSH
替换为string.empty
,则选中复选框2 < / p>