当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > C#初学乍练-文本替换工具命令行版

ASP.NET
FreeTextBox(版本3.1.6)在ASP.Net 2.0中使用方法
.NET 常用功能和代码小结
在 .NET Framework 2.0 中未处理的异常导致基于 ASP.NET 的应用程序意外退出
asp.net IList查询数据后格式化数据再绑定控件
asp.net sql存储过程
asp.net 简单实现禁用或启用页面中的某一类型的控件
asp.net(c#)获取内容第一张图片地址的函数
The remote procedure call failed and did not execute的解决办法
ASP.NET 在线文件管理
asp.net 读取并修改config文件实现代码
ASP.NET Cookie 操作实现
asp.net Silverlight中的模式窗体
Silverlight中动态获取Web Service地址
asp.net Silverlight应用程序中获取载体aspx页面参数
asp.net 水晶报表隔行换色实现方法
asp.net 获取Gridview隐藏列的值
手动把asp.net的类生成dll文件的方法
asp.net 使用ObjectDataSource控件在ASP.NET中实现Ajax真分页
动态指定任意类型的ObjectDataSource对象的查询参数
asp.net Md5的用法小结

ASP.NET 中的 C#初学乍练-文本替换工具命令行版


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 67 ::
收藏到网摘: n/a


该程序使用正则表达式进行文字替换,广度优先遍历子目录(基础知识很重要), 解决无法替换回车换行的问题
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:\temp\ttt", "\r\n);", @"(\r\n){2,}\);", true, true);