C#初学乍练-文本替换工具命令行版

儒雅的忘情水17

儒雅的忘情水17

2016-01-29 12:30

C#初学乍练-文本替换工具命令行版,C#初学乍练-文本替换工具命令行版

该程序使用正则表达式进行文字替换,广度优先遍历子目录(基础知识很重要), 解决无法替换回车换行的问题
class Replacee
{
///
/// 替换文件中字符
///

///
文件全名
///
用于替换的字符串
///
用于查找的字符串
///
是否备份文件
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);
}
}
///
/// 遍历目录
///

///
起始路径
///
用于替换的字符串
///
用于查找的字符串
///
是否备份文件
///
是否获取子文件夹
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:tempttt", "rn);", @"(rn){2,});", true, true);
展开更多 50%)
分享

猜你喜欢

C#初学乍练-文本替换工具命令行版

电脑网络
C#初学乍练-文本替换工具命令行版

C/C++中命令行参数的原理

编程语言 网络编程
C/C++中命令行参数的原理

s8lol主宰符文怎么配

英雄联盟 网络游戏
s8lol主宰符文怎么配

Delphi命令行参数

编程语言 网络编程
Delphi命令行参数

Access命令行参数

电脑网络
Access命令行参数

lol偷钱流符文搭配推荐

英雄联盟 网络游戏
lol偷钱流符文搭配推荐

启动命令行选项

编程语言 网络编程
启动命令行选项

Linux系统命令行Find工具使用小技巧

Linux Linux命令 Linux安装 Linux编程 Linux桌面 Linux软件 Linux内核 Linux管理
Linux系统命令行Find工具使用小技巧

lolAD刺客新符文搭配推荐

英雄联盟
lolAD刺客新符文搭配推荐

《全民飞机大战》金币征战PK场攻略

《全民飞机大战》金币征战PK场攻略

Flash新手入门教程:AS3代码第一课——下雪效果

Flash新手入门教程:AS3代码第一课——下雪效果
下拉加载更多内容 ↓