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)文件不能有單行注釋"http://"
/// 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);
}