批量处理.cs文件中的命名空间排序及诠释

批量处理.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-2015 by BIMCoder, Inc.
//
// System namespaces
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System;

// Autodesk namespaces
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

// BIMCore namespaces
using BIMCore.DB;

// My namespaces
using Revit.Addin.isBIMAppWrapper;


namespace Revit.Addin.isBIM.QuickFilters
{
... ...

 

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

批量处理.cs文件中的命名空间排序及诠释

代码:

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

165行对文件重写时依然使用文件原有编码格式,防止打开文件时候有乱码。


51行的子函数 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

我是怎么判断更新的呢?答案是判断cs文件中是否有“// System namespaces”这句话,如果有的话就不需要更新了。如果大家有更棒的方法也能提供给我。