我有一个代码遍历整个文本文件,以搜索特定的文本“ [名称]”,然后“尝试”以删除文本下方的所有行。我尝试了File.WriteAllText(INILoc,string.Empty);,但这只是删除了整个文本文件中的所有内容。我该如何做才能删除“ [名称]”下的所有行?
我已经设置了像这样的迭代:
string[] lines = File.ReadAllLines(INILoc);
bool containsSearchResul = false;
foreach (string line in lines)
{
if (containsSearchResul)
{
File.WriteAllText(INILoc, string.Empty);
}
if (line.Contains("[names]"))
{
containsSearchResul = true;
}
}
您需要将"[names]"
文本之前的行存储到字符串变量中,并且当条件(line.Contains("[names]"))
满足时,只需中断循环并将字符串值写入同一文件即可。
就像是,
string[] lines = File.ReadAllLines(INILoc); //Considering INILoc is a string variable which contains file path.
StringBuilder newText = new StringBuilder();
bool containsSearchResul = false;
foreach (string line in lines)
{
newText.Append(line);
newText.Append(Environment.NewLine); //This will add \n after each line so all lines will be well formatted
//Adding line into newText before if condition check will add "name" into file
if (line.Contains("[names]"))
break;
}
File.WriteAllText(INILoc, newText.ToString());
//^^^^^^^ due to string.Empty it was storing empty string into file.
注意:如果您使用的是StringBuilder
课堂,那么不要错过添加Using System.Text
您的程序的机会
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句