批量替换大文件夹内的查找和批量替换,支持模糊查询。
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“请输入替换的路径”);
string dirPath = Console.ReadLine();
Console.WriteLine(“请输入待替换的文件名,支持模糊查询”);
string fileName = Console.ReadLine();
Console.WriteLine(“请输入待替换的文本”);
string textOld = Console.ReadLine();
Console.WriteLine(“请输入新的文本”);
string textNew = Console.ReadLine();
SearchReplace(dirPath, fileName, textOld, textNew);
Console.WriteLine(“全部替换完成!”);
Console.ReadKey();
}
static void SearchReplace(string dirPath,string fileName,string textOld,string textNew)
{
try
{
foreach (string d in Directory.GetDirectories(dirPath))
{
foreach (string f in Directory.GetFiles(d,”*”+fileName+”*”))
{
Console.WriteLine(f);
TextReplace(f, textOld, textNew);
}
SearchReplace(d,fileName,textOld,textNew); //递归查询 调用自己
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void TextReplace(string filePath, string textOld, string textNew)
{
try
{
string content = File.ReadAllText(filePath, Encoding.UTF8);
if (content.Contains(textNew))
{
Console.WriteLine(“has been replaced.”);
}
else if (content.Contains(textOld))
{
content = content.Replace(textOld, textNew);
File.WriteAllText(filePath, content, Encoding.UTF8);
Console.WriteLine(“is replaced.”);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}