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);