public static String Replace(String source,String oldStr,String newStr)
{
int count = Regex.Matches(source, oldStr).Count;
for (int i = 0; i count; i++)
{
source = source.Replace(oldStr, newStr);
}
return source;
}
/// summary>
/// 压缩指定路径的文件空白字符串和换行符
/// 压缩说明
/// 1)采取File.ReadAllLines读取所有行每一行做处理工作
/// 2)服务器控件最好写在一行内,只做了尾部标签与runat="server"跨行的处理,开始标签跨行为处理
/// 3)文件不能有单行注释"//"
/// 4)替换掉了换行符和空格
/// /summary>
/// param name="filePath">文件路径/param>
public static void CompressLineByLine(String filePath)
{
if (!File.Exists(filePath))
{
Console.WriteLine("文件不存在,检查路径{0}", filePath);
return;
}
var start = DateTime.Now;
Console.WriteLine("正在压缩文件:{0}\r\n开始于{1}...",
filePath,start.ToString());
var lines = File.ReadAllLines(filePath,
Encoding.GetEncoding("GB2312"));
for (int i = 0; i lines.Length; i++)
{
var item = lines[i].Trim();
if (item.IndexOf("runat=\"server\"") > -1)
item += " ";
item = item.Replace("\r\n", "");
item = Replace(item, " ", " ");
lines[i] = item;
}
File.WriteAllText(filePath, string.Join("", lines),
Encoding.GetEncoding("GB2312"));
var end = DateTime.Now;
Console.WriteLine("结束于{0}...", end.ToString());
Console.WriteLine("====耗时====\r\n{0}\r\n", end - start);
}
/// summary>
/// 压缩指定路径的文件空白字符串和换行符
/// 压缩说明
/// 1)一次性读取出所有的文本替换掉换行符和空白
/// 2)无须处理服务器控件换行的问题
/// 3)压缩不彻底,A元素的结束标签和B开始标签之间可能仍然有一个空格
/// /summary>
/// param name="filePath">/param>
public static void CompressAtOneTime(String filePath)
{
var start = DateTime.Now;
Console.WriteLine("正在压缩文件:{0}\r\n开始于{1}...", filePath,
start.ToString());
var lines = File.ReadAllText(filePath);
File.WriteAllText(filePath, Replace(Replace(lines, "\r\n",
"")," "," "), Encoding.GetEncoding("GB2312"));
var end = DateTime.Now;
Console.WriteLine("结束于{0}...", end.ToString());
Console.WriteLine("====耗时====\r\n{0}\r\n", end - start);
}