using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
namespace Check_3_1
{
class Program
{
//private static int sumLines = 0;
private static int emptyLines = 0;
private static int noteLines = 0;
private static int codeLines = 0;
static void Main(string[] args)
{
// FileStream fs = new FileStream("C:\\Users\\Sam\\Desktop\\1.txt", FileMode.Open);
calculate();
}
public static void calculate()
{
string sum;
string a = null;
string b = null;
bool bl = false;
//用于最后的输出判定
int n=0;
string[] AllFile=null;
Console.WriteLine("输入目录或文件的完整路径:");
a = Console.ReadLine();
if (Directory.Exists(a))//判定是目录
{
AllFile = Directory.GetFiles(@a);
// 读取目录下的所有文件的文件路径,存放在字符串数组
n = AllFile.Length;
Console.WriteLine("输入文件类型(例如:.cs):");
b = Console.ReadLine();
}
else //判定是文件
{
AllFile = new string[1];
//实例化
AllFile[0] = a;
//由于是文件,所以只有一个路径
n = 1;
b = Path.GetExtension(a);
//把该文件的后缀赋值给b
}
bool note = false;
//用于判断注释中的/**/
for (int j = 0; j < n; j++)
//当选项一输入为一个文件而非目录时,只执行一次
{
try
{
FileInfo fi = new FileInfo(AllFile[j]);
if (fi.Extension == b)
// 只有后缀和b一样的文件能读取,其他文件省略
{
bl = true;
//判定后缀名符合要求
Console.WriteLine("文件路径:" + AllFile[j]);
StreamReader sr = File.OpenText(@AllFile[j]);
// 定义流文件
try
{
// 下面是空格行,注释行,还有代码行的判定
while ((sum = sr.ReadLine()) != null)
{
sum = sum.Trim();
//去除字符串首尾的空格,方便判断
if (Regex.IsMatch(sum, "^[\\n]*$"))
//正则表达式含义为只有回车键
{
emptyLines++;
}
else if (sum.StartsWith("/*") && !sum.EndsWith("*/"))
//注释行
{
noteLines++;
note = true;
}
else if (note == true)
{
noteLines++;
if (sum.EndsWith("*/"))
{
note = false;
}
}
else if (sum.StartsWith("//"))
{
noteLines++;
}
else
//除了上述情况都视为代码行
{
codeLines++;
}
}
}
catch (Exception e)
{
throw new Exception("抛出异常");
}
sr.Close();
}
}
catch (Exception e)
{
throw new Exception("抛出异常");
}
finally
{
if (bl)
//符合要求的文件则输出其信息
{
Console.WriteLine("空行数:" + emptyLines);
emptyLines = 0;
Console.WriteLine("注释行数:" + noteLines);
noteLines = 0;
Console.WriteLine("代码行数:" + codeLines);
codeLines = 0;
Console.WriteLine();
bl = false;
}
}
}
Console.Read();
//仅用于编译之后滞留在控制台而非闪退
}
}
}