zoukankan      html  css  js  c++  java
  • 【Winform】.cs文件命名空间排序及注释批量处理工具

    公司里每个程序员在命名空间的排序和注释上都有很多的不同。

    杂乱的命名空间:

    using System;
    using System.Collections.Generic;
    using Autodesk.Revit.UI;
    using BIMCore.UI.ModelessForm;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading;
    using RevitDocument = Autodesk.Revit.DB.Document;
    using Autodesk.Revit.DB;
    using BIMCore.UI;
    using BIMCore.DB;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using BIMCore.DB.Geometry;
    using Res = Revit.Addin.isBIM.QuickFilters.Properties.Resources;
    using BIMCore.DB.Log;
    
    
    namespace Revit.Addin.isBIM.QuickFilters
    {
        public partial class CustomForm : System.Windows.Forms.Form
        {
            RevitDocument rvtDoc_temp = null;
            public List<int> Resultlist = null;
            public List<int> Existinglist = null;
            
    ...   ....

    有序的命名空间:

    //
    // (C) Copyright 2010-2016 by XXX, Inc.
    //
    // System namespaces
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    // Autodesk namespaces
    using Autodesk.Revit.DB;
    using Autodesk.Revit.UI;
    using Autodesk.Revit.UI.Selection;
    
    // BIMCore namespaces
    using BIMCore.DB;
    using BIMCore.DB.Geometry;
    
    // My namespaces
    using Res = Revit.Addin.isBIM.PowerMeasure.Properties.Resources;
    using Revit.Addin.isBIM.PowerMeasure.Views;
    using Revit.Addin.isBIMAppWrapper;
    
    namespace Revit.Addin.isBIM.PowerMeasure
    {
    
    ...  ...

    为了方便管理代码,这里我制作了一个批量处理.cs文件中命名空间排序及注释的工具。

    代码:

      1 private void buttonConfirm_Click(object sender, EventArgs e)
      2         {
      3             string strfilepath = textBoxFilePath.Text;
      4             List<string> liststrdocuments = new List<string>();
      5             progressBarFiles.Visible = true;
      6             if (!string.IsNullOrWhiteSpace(textBoxFilePath.Text) && System.IO.Directory.Exists(textBoxFilePath.Text))  //判断路径是否为空或者是否存在
      7             {
      8                 if (!string.IsNullOrWhiteSpace(textBoxNameSpace.Text))
      9                 {
     10                     string[] strdocuments = Directory.GetFiles(strfilepath, "*.cs",SearchOption.AllDirectories); //得到文件夹路径下的所有cs文件路径
     11                     if (strdocuments.Length == 0)                                                                //判断文件夹中是否没有cs文件
     12                     {
     13                         progressBarFiles.Visible = false; 
     14                         MessageBox.Show(Properties.Resources.StringFileExist);
     15                     }
     16                     else
     17                     {
     18                             foreach (string strdocu in strdocuments)        //排除部分cs文件,其中obj文件夹下的cs文件直接忽略
     19                             {
     20                                 if(boolMode==true)
     21                                 {
     22                                     if (!strdocu.Contains("AssemblyInfo") && !strdocu.Contains("Designer") && !strdocu.Contains("obj") && !strdocu.Contains("designer"))
     23                                     {
     24                                         liststrdocuments.Add(strdocu);
     25                                     }
     26                                 }
     27                                 else
     28                                 {
     29                                     if(!strdocu.Contains("obj"))
     30                                     {
     31                                        liststrdocuments.Add(strdocu);
     32                                     }                         
     33                                 }                  
     34                             }
     35                                           
     36                         for (int i = 0; i < liststrdocuments.Count; i++)        //改变文件只读属性
     37                         {
     38                             if (File.GetAttributes(liststrdocuments[i]).ToString().IndexOf("ReadOnly") != -1)
     39                             {
     40                                 File.SetAttributes(liststrdocuments[i], FileAttributes.Normal);
     41                             }
     42                         }
     43                         int intprogress = 0;
     44                         progressBarFiles.Maximum = liststrdocuments.Count;
     45                         DataTable dt = new DataTable();
     46                         dt.Columns.Add((Properties.Resources.StringDatagridViewCellHeaderOne), typeof(string));
     47                         dt.Columns.Add((Properties.Resources.StringDatagridViewCellHeaderTwo), typeof(string));
     48                         string strupdatestatus = null;
     49 
     50                         foreach (string Documentpath in liststrdocuments)               //遍历每个路径
     51                         {
     52                             System.Text.Encoding fileEncoding = GetFileEncodeType(Documentpath);  //获取该文件的编码格式
     53                             intprogress++;
     54                             progressBarFiles.Value = intprogress;
     55                             string namespacerest = null;
     56                             string strusingsystem = null;
     57                             string strusingAutodesk = null;
     58                             string strusingBIMCore = null;
     59                             string strusingrest = null;
     60                             string namespaceresult = string.Empty;
     61                             string textboxcopyright = textBoxNameSpace.Text;
     62                             
     63                             List<string> listtempline = new List<string>();
     64                             List<string> listnamespacerest =  new List<string>();
     65                             List<string> namespacesurplus = new List<string>();
     66 
     67 
     68                             if (DocumentChanged(Documentpath) == false)
     69                             {
     70                                 strupdatestatus = Properties.Resources.StringUpdateStatusOne;
     71                                 dt=BuildDataTable(dt,Documentpath,strupdatestatus);
     72                             }
     73                             else
     74                             {
     75                                 string[] lines = File.ReadAllLines(Documentpath);       //根据路径,分行读取该文件
     76                                 foreach (string line in lines)
     77                                 {
     78                                     if (line.StartsWith("using"))
     79                                     {
     80                                         listtempline.Add(line);  //得到命名空间的行
     81                                     }
     82                                     else if (!string.IsNullOrWhiteSpace(line))
     83                                     {
     84                                         listnamespacerest.Add(line);  //记录剩下的部分
     85                                     }
     86                                     strupdatestatus = Properties.Resources.StringUpdateStatusTwo;
     87                                 }
     88 
     89                                 #region   对namespace中的多余部分进行处理,保留没有空行的部分
     90                                 foreach (string line in listnamespacerest)
     91                                 {
     92                                     if (line.StartsWith("namespace") || line.StartsWith("["))
     93                                     {
     94                                         break;
     95                                     }
     96                                     else if (!string.IsNullOrWhiteSpace(line))
     97                                     {
     98                                         namespacesurplus.Add(line);
     99                                     }
    100                                 }
    101                                 if (namespacesurplus.Count != 0)
    102                                 {
    103                                     for (int i = 0; i < listnamespacerest.Count; i++)
    104                                     {
    105                                         for (int j = 0; j < namespacesurplus.Count; j++)
    106                                         {
    107                                             if (namespacesurplus[j] == listnamespacerest[i])
    108                                             {
    109                                                 listnamespacerest.RemoveAt(i);
    110                                             }
    111                                         }
    112                                     }
    113                                 }
    114                                 foreach (string line in listnamespacerest)
    115                                 {
    116                                     namespacerest += line + "
    ";
    117                                 }
    118                                 #endregion
    119 
    120 
    121                                 listtempline.Sort(delegate(string str1, string str2)     //对命名空间进行排序
    122                                 {
    123                                     return Comparer<string>.Default.Compare(str1.Trim(';'), str2.Trim(';'));
    124                                 });
    125 
    126 
    127                                 foreach (string line in listtempline)  //对命名空间行归类
    128                                 {
    129                                     if (line.StartsWith("using System"))
    130                                     {
    131                                         strusingsystem += line + "
    ";
    132                                     }
    133                                     else if (line.StartsWith("using Autodesk"))
    134                                     {
    135                                         strusingAutodesk += line + "
    ";
    136                                     }
    137                                     else if (line.StartsWith("using BIMCore"))
    138                                     {
    139                                         strusingBIMCore += line + "
    ";
    140                                     }
    141                                     else
    142                                     {
    143                                         strusingrest += line + "
    ";
    144                                     }
    145                                 }
    146                                 string strusingAutodeskresult;
    147                                 string strusingBIMCoreresult;
    148                                 string strusingrestresult;
    149                                 strusingAutodeskresult = strusingBIMCoreresult = strusingrestresult = string.Empty;
    150                                 string strusingsystemresult = "// System namespaces" + "
    " + strusingsystem + "
    ";
    151 
    152                                 if (!string.IsNullOrWhiteSpace(strusingAutodesk))
    153                                 {
    154                                     strusingAutodeskresult = strusingAutodesk;
    155                                     strusingAutodeskresult = "// Autodesk namespaces" + "
    " + strusingAutodesk + "
    ";
    156                                 }
    157                                 if (!string.IsNullOrWhiteSpace(strusingBIMCore))
    158                                 {
    159                                     strusingBIMCoreresult = strusingBIMCore;
    160                                     strusingBIMCoreresult = "// BIMCore namespaces" + "
    " + strusingBIMCore + "
    ";
    161                                 }
    162                                 if (!string.IsNullOrWhiteSpace(strusingrest))
    163                                 {
    164                                     strusingrestresult = strusingrest;
    165                                     strusingrestresult = "// My namespaces" + "
    " + strusingrestresult + "
    ";
    166                                 }
    167                                 namespaceresult = textboxcopyright + "
    " + strusingsystemresult +                      //重写文件
    168                                                   strusingAutodeskresult + strusingBIMCoreresult + strusingrestresult + namespacerest;
    169                                 File.WriteAllText(Documentpath, namespaceresult, fileEncoding);
    170 
    171                                 textboxcopyright = strusingsystem = strusingAutodesk = strusingBIMCore = strusingrest = namespacerest = string.Empty; //变量清空
    172                                 dt=BuildDataTable(dt, Documentpath, strupdatestatus);                                                          
    173                                
    174                             }
    175                             
    176                         }
    177 
    178                         #region  控件属性的设置
    179                         dataGridViewfiles.DataSource = dt;               //datagridview的设置
    180                         dataGridViewfiles.AllowUserToAddRows = false;   
    181                         dataGridViewfiles.RowHeadersVisible = false;
    182                         dataGridViewfiles.AllowUserToResizeColumns = false;
    183                         dataGridViewfiles.AllowUserToResizeRows = false;
    184                         dataGridViewfiles.Columns[1].Width = Convert.ToInt32(Math.Ceiling(0.3 * Convert.ToDouble(dataGridViewfiles.Width)));  //设定更新状态栏的列宽
    185                         dataGridViewfiles.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;  //设定更新状态栏的字体居中                            
    187                         progressBarFiles.Visible = false;
    192                         #endregion
    193                     }
    194                 }
    195                 else
    196                 {
    197                     progressBarFiles.Visible = false;  
    198                     MessageBox.Show(Properties.Resources.StringTextBoxCopyrightStauts);
    199                 }          
    200             }
    201             else
    202             {
    203                 progressBarFiles.Visible = false;  
    204                 MessageBox.Show(Properties.Resources.StringTextBoxFileStatus);
    205             }            
    206         }

    169行对文件重写时依然使用文件原有编码格式,防止打开文件时候有乱码。
    52行的子函数 GetFileEncodeType(string filename)判断编码格式    函数转载地址:http://www.cnblogs.com/swtseaman/archive/2011/05/17/2048689.html

     public System.Text.Encoding GetFileEncodeType(string filename) 
           {
               System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite); 
               //FileShare.ReadWrite, 不然文件在进行其他IO操作时进程会被占用而报错
    
               System.IO.BinaryReader br = new System.IO.BinaryReader(fs); 
               Byte[] buffer = br.ReadBytes(2); 
               if(buffer[0]>=0xEF) 
               { 
                   if(buffer[0]==0xEF && buffer[1]==0xBB) 
                   { 
                        return System.Text.Encoding.UTF8; 
                   } 
                   else if(buffer[0]==0xFE && buffer[1]==0xFF) 
                   { 
                        return System.Text.Encoding.BigEndianUnicode; 
                   } 
                   else if(buffer[0]==0xFF && buffer[1]==0xFE) 
                   { 
                        return System.Text.Encoding.Unicode; 
                   } 
                   else
                   { 
                        return System.Text.Encoding.Default; 
                   } 
               } 
               else
               { 
                     return System.Text.Encoding.Default; 
               }
           }
            #endregion

    68行为文件更新判据:判断cs文件中是否有“// System namespaces”, 还有就是cs文件中的copyright部分是否与winform中的copyright文本框内容相同。

     1 private bool DocumentChanged(string path)
     2         {  
     3             bool boolWholeStatus = true;
     4             bool boolStatus1 = false;
     5             bool boolStatus2 = false;
     6             string oralcopyright = string.Empty;
     7             string txtnamspace = textBoxNameSpace.Text+"
    ";
     8             string[] lines = File.ReadAllLines(path);       //根据路径,分行读取该文件
     9             
    10             foreach (string line in lines)
    11             {
    12                 if (line.StartsWith("// System namespaces") || line.StartsWith("// System Namespaces") || line.StartsWith("//System namespaces") || 
    line.StartsWith("//System Namespaces")) 13 { 14 boolStatus2 = true; 15 break; 16 } 17 else if(!string.IsNullOrEmpty("line")) 18 { 19 oralcopyright += line + " "; 20 } 21 } 22 if (txtnamspace.Equals(oralcopyright)) 23 { 24 boolStatus1 = true; 25 } 26 27 if (boolStatus1 == true && boolStatus2 == true) 28 { 29 boolWholeStatus = false; 30 } 31 return boolWholeStatus; 32 }

    71行的datatable构建方法:

    private DataTable BuildDataTable(DataTable dt, string path, string status)
            {
                DataRow dr = dt.NewRow();
                dr[Properties.Resources.StringDatagridViewCellHeaderOne] = path;
                dr[Properties.Resources.StringDatagridViewCellHeaderTwo] = status;
                dt.Rows.Add(dr);
                return dt;
            }
  • 相关阅读:
    UVa 10118 记忆化搜索 Free Candies
    CodeForces 568B DP Symmetric and Transitive
    UVa 11695 树的直径 Flight Planning
    UVa 10934 DP Dropping water balloons
    CodeForces 543D 树形DP Road Improvement
    CodeForces 570E DP Pig and Palindromes
    HDU 5396 区间DP 数学 Expression
    HDU 5402 模拟 构造 Travelling Salesman Problem
    HDU 5399 数学 Too Simple
    CodeForces 567F DP Mausoleum
  • 原文地址:https://www.cnblogs.com/lovecsharp094/p/5427462.html
Copyright © 2011-2022 走看看