我写了一个方法,它会遍历所有文本文件,替换文本,并用所述更改更新文本框。它在我第一次运行之后起作用,但随后的执行似乎推断文件没有第一次更改。替换文件中的文本
private void changeText(string searchString, string newString, FileInfo[] listOfFiles)
{
foreach (FileInfo tempfi in listOfFiles)//Foreach File
{
string fileToBeEdited = tempfi.FullName;
File.SetAttributes(fileToBeEdited, File.GetAttributes(fileToBeEdited) & ~FileAttributes.ReadOnly); //Remove ReadOnly Property
string strFile = System.IO.File.ReadAllText(fileToBeEdited); //Reads In Text File
if(strFile.Contains(newString))//If the replacement string is contained in the text file
{
strFile = strFile.Replace(searchString, newString);
System.IO.File.WriteAllText(fileToBeEdited, strFile); //Write changes to File
myTextBox.Text = "File Changed: " + fileTobeEdited.ToString() + Environment.NewLine; //Notify User
}
}
}
如果我运行这1次或100次我的文本文件更新就好了。如果我第二次运行这个文本框,它会重新更新,说它更新了新文件。
我希望这种方法在第一次运行后不会找到任何要替换的文本。
它不会出现您实际上替换文件中的任何内容。所以,你实际上每次都找到相同的内容。 – PhoenixReborn
您不会对文件进行任何更改。您将其数据读取到strFile,检查strFile是否包含一些字符串,将srtFile保存回文件。没有编辑 – Steve
对不起(这是在我的代码中,但没有在我的初始文章 – Demasterpl