日期:2014-05-18 浏览次数:20972 次
using System; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //总行数 int totalLineCount = 0; //目录 string directory; if (args.Length > 0) { directory = args[0]; } else { directory = Directory.GetCurrentDirectory(); } totalLineCount = DirectoryCountLines(directory); Console.WriteLine(totalLineCount); Console.ReadLine(); } /// <summary> /// 计算目录数 /// </summary> /// <param name="directory"></param> /// <returns></returns> static int DirectoryCountLines(string directory) { //这里的变量不是每次方法运行一次就会把次赋为0吗?为什么还可以累加上次的结果。 int lineCount = 0; foreach (string file in Directory.GetFiles(directory, "*.txt")) { lineCount += CountLines(file); } //递归子目录 foreach (string subdirectory in Directory.GetDirectories(directory)) { lineCount += DirectoryCountLines(subdirectory); } return lineCount; } /// <summary> /// 计算行数 /// </summary> /// <param name="file"></param> /// <returns></returns> private static int CountLines(string file) { string line; int lineCount = 0; FileStream stream = new FileStream(file, FileMode.Open); StreamReader reader = new StreamReader(stream); line = reader.ReadLine(); while (line != null) { if (line.Trim() != "") { lineCount++; } line = reader.ReadLine(); } reader.Close(); return lineCount; } } }