使用C#WinForms程序读取代码行数(如.txt文件,.cs,.java,.c等文件)

来源:互联网 发布:网络推广方法大全 编辑:程序博客网 时间:2024/05/23 01:24

   朋友们大家好,如何计算多个文件的代码行数,如果一个一个去计算,那一定会很烦琐,如有用一个小工具来统计就很简单了,也很省心,小弟在此献上自已在开发过程中制作的一个计算文件代码行数
的小程序供大家参考

 //StringBuilder用来暂时保存操作文件路径和文件代码行数
  private System.Text.StringBuilder result = new System.Text.StringBuilder(200);
  private int sumFileCount = 0;                                                                                    //统计子文件数
  private int sumLineCount = 0;                                                                                  //统计代码行数

  private void button1_Click(object sender, System.EventArgs e)
  {
   
   this.txtFind.Text = "";

   //选择文件路径
   this.fobDialog.ShowDialog();

   //将选择的文件路径赋给textBox
   this.txtPath.Text = this.fobDialog.SelectedPath.ToString();

   string path = this.txtPath.Text.Trim().ToString();
   
   //调用GetPath方法
   GetPath(path);
  }
  
  private void GetPath(string path)
  {
   if(path.Equals("") || path.Length == 0)
   {
    MessageBox.Show("请选择你的路径!!!");
    return;
   }
   //使用DirectoryInfo对象得到文件
   DirectoryInfo directoryinfo = new DirectoryInfo(path);
   
   try
   {
    //如果文件存在,调用DirectoryRecursion()方法,并显示数据
    if(directoryinfo.Exists)
    {
     this.txtFind.Text = "正在读取中,请稍后....................";
     DirectoryRecursion(directoryinfo);
     this.txtFind.Text = result.ToString();
     this.txtFind.Text += "总文件数是 :" + sumFileCount.ToString() + " 代码总代码行数为:" + sumLineCount.ToString();
    }
    else
    {
     MessageBox.Show("你查找的文件不存在!!!!!");
     return;
    }
   }
   catch(Exception ex)
   {
    MessageBox.Show(ex.Message);
    return;
   }
  }
  private void DirectoryRecursion(DirectoryInfo dir)
  {
   //得到路径下的所有文件列表
   FileInfo[] files = dir.GetFiles();

   //得到代码行数
   int LineCount = 0;

   //创建StreamReader用来读取文件
   StreamReader fileReader;

   //循环得到此目录下的所有文件
   foreach(FileInfo file in files)
   {

    //判断文件扩展名,可更改
    if(file.Extension.Trim().ToLower().Equals(".cs") || file.Extension.Trim().ToLower().Equals(".txt") || file.Extension.Trim().ToLower().Equals(".sql"))
    {
     LineCount = 0;
     try
     {
      fileReader = file.OpenText();

      //循环读取文件中代码行数
      while(fileReader.ReadLine() != null)
      {
       //统计文件代码行数
       LineCount++;
      }
     }
     catch(Exception ex)
     {
      MessageBox.Show(ex.Message);
      return;
     }
     //将数据添加到result中
     result.AppendFormat(file.FullName + "文件中的代码行数是" + LineCount + System.Environment.NewLine);
     this.sumFileCount++;
     this.sumLineCount += LineCount;
    }
   }

   //得到文件下的子文件夹
   DirectoryInfo[] dirs = dir.GetDirectories();

   //如果此文件夹下有子文件夹,则循环递归调用
   if(dirs.Length != 0)
   {
    foreach(DirectoryInfo info in dirs)
    {
      DirectoryRecursion(info);
    }
   }
   //如果此文件夹下没有子文件夹,退出递归
   else
   {
    return;
   }
  }

   

原创粉丝点击