您的位置:首页 > 编程语言

统计代码文件的注释行

2014-03-02 00:24 204 查看
涉及了并行处理、lambda表达式、LINQ、字典集合、using语句、文件处理、匿名类型等知识点。

功能:统计指定目录下(包括子目录)所有.CS文件中的以\\开头的注释行

源码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Cryking
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入工程所在的目录:");
string strPath=Console.ReadLine();
string[] astrFile = Directory.GetFiles(strPath,"*.cs",SearchOption.AllDirectories);
var files = from f in astrFile   //LINQ
where !f.ToLower().Contains(".designer.cs")
select f;
Dictionary<string, int[]> dic = new Dictionary<string, int[]>();
DateTime dt = DateTime.Now;

Parallel.ForEach(files, strFile =>//并行处理+lambda表达式
{
Console.WriteLine("正在搜索文件:{0}", strFile);
using (StreamReader sr = new StreamReader(strFile, Encoding.Default))
{
string s;
int[] Count = new int[4] { 0, 0, 0, 0 };
int conCount = 0;
bool flag = false;//连续注释标志
while (null != (s = sr.ReadLine()))
{
if (s.Trim().Equals(""))
Count[3]++;
else if (s.Trim().Length >= 2
&& s.Trim().Substring(0, 2) == @"//")
{
if (flag)
{
conCount++;
Count[1] = Math.Max(conCount, Count[1]);
}
else
conCount = 0;
Count[2]++;
flag = true;
}
else
flag = false;

Count[0]++;
}
dic.Add(strFile, Count);
}
});

StreamWriter sw = new StreamWriter("SearchComm.txt",true, Encoding.Default);
long sumLines = 0;
foreach (KeyValuePair<string, int[]> kvp in dic)
{
sw.WriteLine("file={0}  行数={1}, 最大连续注释行数={2}, 总注释行数={3}, 空白行数={4}",
kvp.Key, kvp.Value[0], kvp.Value[1], kvp.Value[2], kvp.Value[3]);
sumLines += kvp.Value[0];
}
sw.WriteLine("{0}","-".PadLeft(15,'-'));
string sumTime=(DateTime.Now - dt).TotalSeconds.ToString();
sw.WriteLine("搜索总文件数:{0},总行数:{1},总耗时{2}秒", files.Count(), sumLines, sumTime);
sw.Close();
Console.WriteLine("搜索完成!\n搜索总文件数:{0},共耗时{1}秒.",files.Count(), sumTime);
Console.ReadKey();
}
}
}

稍微试了下:

---------------

搜索总文件数:750,总行数:593673,总耗时0.8110464秒
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: