国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 山东| 张北县| 黄龙县| 宁化县| 徐州市| 含山县| 西藏| 太康县| 澎湖县| 股票| 原平市| 汶上县| 和顺县| 贺州市| 呈贡县| 连平县| 泸水县| 张家川| 尼玛县| 松阳县| 台北市| 孟州市| 苍山县| 黔东| 济宁市| 大埔区| 姜堰市| 岑溪市| 潼关县| 南京市| 莱西市| 安远县| 通许县| 衡阳市| 姚安县| 武义县| 常宁市| 京山县| 常宁市| 锡林郭勒盟| 达日县|