代码如下,主要的调用方法是searchReplace,
private void btnSure_Click(object sender, System.EventArgs e)

{
try

{
string folderPath = txt_folder.Text;
DirectoryInfo theFolder = new DirectoryInfo(folderPath);//目录名称
string str1=txtString1.Text;//不包含字符串;
string str2=txtString2.Text;//要替换的字符串;
string str3=txtString3.Text;//替换成字符串;
if (theFolder.Exists)

{
searchReplace(theFolder.FullName,str1,str2,str3);
}
MessageBox.Show("处理成功!");
}
catch(Exception ex)

{
MessageBox.Show(ex.Message);
}
}
void searchReplace(string strFolder,string str1,string str2,string str3)

{
DirectoryInfo theFolder = new DirectoryInfo(strFolder);//根目录名称
FileInfo[] fis = theFolder.GetFiles();//找到该目录下所有文件
foreach (FileInfo fi in fis) //循环

{ //begin for
bool blDo=true;
StringBuilder sb = new StringBuilder();
StreamReader sr =new StreamReader(fi.FullName,Encoding.GetEncoding("GB2312"));
string s = "";
while ((s = sr.ReadLine()) != null)

{
if(s.IndexOf(str1)!=-1)

{
blDo=false; //找到有str1字符的文件了,
}
int intPos=s.IndexOf(str2);
if(intPos!=-1)

{
s=s.Replace(str2,str3); //替换
}
sb.Append(s+"\r\n");//将替换后的所有写入到StringBuilder中.
}//end while
sr.Close();
if(blDo)

{
// MessageBox.Show(sb.ToString());
StreamWriter sw = new StreamWriter(fi.FullName,false,Encoding.GetEncoding("GB18030"));
sw.Write(sb);//如果是要替换的文件,将StringBuilder回写到文件中。
sw.Close();
}
}//end for
//递归调用
foreach(DirectoryInfo nextFolder in theFolder.GetDirectories())

{
searchReplace(nextFolder.FullName,str1,str2,str3);
}
源代码工程:https://files.cnblogs.com/l_dragon/Solution1.rar