C#初学乍练-文本替换工具命令行版
2024-07-21 02:18:55
供稿:网友
该程序使用正则表达式进行文字替换,广度优先遍历子目录(基础知识很重要), 解决无法替换回车换行的问题
class replacee
{
/// <summary>
/// 替换文件中字符
/// </summary>
/// <param name="filefullname">文件全名</param>
/// <param name="replacedby">用于替换的字符串</param>
/// <param name="findpattern">用于查找的字符串</param>
/// <param name="isbackup">是否备份文件</param>
private static void doreplace(string filefullname, string replacedby, string findpattern, bool isbackup)
{
string result = string.empty;
string inputtext = string.empty;
string replacement = replacedby;
string pat = findpattern;
regex r = new regex(pat, regexoptions.ignorecase);
try
{
using (streamreader sr = new streamreader(filefullname))
{
inputtext = sr.readtoend();
}
// compile the regular expression.
if (r.ismatch(inputtext))
{
if (isbackup == true)
{
try
{
file.copy(filefullname, filefullname + ".bak");
}
catch(system.io.ioexception ex)
{
file.copy(filefullname, filefullname + ".bak", true);
console.writeline(ex.message);
}
}
result = r.replace(inputtext, replacement);
// add some text to the file.
using (streamwriter sw = new streamwriter(filefullname))
{
sw.write(result);
}
}
console.writeline(filefullname);
}
catch (exception e)
{
console.writeline("the process failed: {0}", e.tostring());
//throw(e);
}
}
/// <summary>
/// 遍历目录
/// </summary>
/// <param name="path">起始路径</param>
/// <param name="replacedby">用于替换的字符串</param>
/// <param name="findpattern">用于查找的字符串</param>
/// <param name="isbackup">是否备份文件</param>
/// <param name="isgetsubfloder">是否获取子文件夹</param>
public static void travelreplace(string path, string replacedstr, string findpattern, bool isbackup, bool isgetsubfloder)
{
queue queue = new queue();
directoryinfo di = null;
string subpath = string.empty;
string currentpath = string.empty;
filesysteminfo[] dirs = null;
queue.enqueue(path);
while (queue.count > 0)
{
currentpath = (string)queue.dequeue();
di = new directoryinfo(currentpath);
//get files under current directiory
filesysteminfo[] files = di.getfiles("*.sql");
foreach (filesysteminfo f in files)
{
doreplace(f.fullname, replacedstr, findpattern, isbackup);
}
// get only subdirectories
if (isgetsubfloder == true)
{
dirs = di.getdirectories();
foreach (filesysteminfo d in dirs)
{
subpath = d.fullname;
queue.enqueue(subpath);
console.writeline(subpath);
}
}
}
}
}
测试:
replacee.travelreplace(@"e:/temp/ttt", "/r/n);", @"(/r/n){2,}/);", true, true);