批量處理.cs文件中的命名空間排序及註釋

来源:http://www.cnblogs.com/lovecsharp094/archive/2016/04/24/5427462.html
-Advertisement-
Play Games

公司里每個程式員在命名空間的排序和註釋上都有很多的不同。 雜亂的命名空間: 有序的命名空間: 為了方便管理代碼,這裡我製作了一個批量處理.cs文件中命名空間排序及註釋的工具。 代碼: 我是怎麼判斷更新的呢?答案是判斷cs文件中是否有“// System namespaces”這句話,如果有的話就不需 ...


公司里每個程式員在命名空間的排序和註釋上都有很多的不同。

雜亂的命名空間:

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文件中命名空間排序及註釋的工具。

代碼:

  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)判斷編碼格式

 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”這句話,如果有的話就不需要更新了。如果大家有更棒的方法也能提供給我。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Chapter 05 變數的更多內容 5.1類型轉換 1.無論什麼類型,所有的數據都是一系列的位,即一組0和1。變數的含義是通過解釋這些數據的方式來傳達的。最簡單的示例是char類型,這種類型用一個數字表示Unicode字元集中的一個字元。實際上,這個數字與ushort的存儲方式相同 他們都是存儲0 ...
  • AnkhSVN是一款在VS中管理Subversion的插件,您可以在VS中輕鬆的提交、更新、添加文件,而不用在命令行或資源管理器中提交。而且該插件屬於開源項目。AnkhSvn安裝下載完畢後,進行安裝,安裝嚮導安裝即可,如下步驟。【步驟1】安裝界面,見圖。 【步驟2】安裝成功 AnkhSvn連接Vis ...
  • ASP.NET 頁運行時,此頁將經歷一個生命周期,在生命周期中將執行一系列處理步驟。這些步驟包括初始化、實例化控制項、還原和維護狀態、運行事件處理程式代碼以及進行呈現。瞭解頁生命周期非常重要,因為這樣做您就能在生命周期的合適階段編寫代碼,以達到預期效果。此外,如果您要開發自定義控制項,就必須熟悉頁生命周 ...
  • 距離上一篇OpenAuth.net的文章已經有5個多月了,在這段時間里項目得到了很多朋友的認可,開源中國上面的Star數接近300,於是堅定了我做下去的信心。最近稍微清閑點,正式推出1.0版,併在阿裡雲上部署了一個線上演示(文章結尾處給出線上演示鏈接)。相比剛開始時的版本,現在整個架構已經穩定,系統 ...
  • 一、線上聊天室 1、新建解決方案 SignalROnlineChatDemo 2、新建MVC項目 SignalROnlineChatDemo.Web (無身份驗證) 3、安裝SignalR PM> install-package Microsoft.AspNet.SignalR 4、 創建一個稱為 ...
  • 調試網站時,異常出現:Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive. Server Error in '/' Application. Configuration Erro ...
  • 概要 有些開發者在編寫方法時,可能較少地去思考一個問題:方法放在這個class中是否合適? 他們可能會覺得:這個方法已經實現xxx功能了,放在哪個class都一樣的,class不就是一個裝方法的容器嘛。 我贊同class是一個裝東西的容器,且不僅限於方法。 但是,容器是有區別的。本文要講的“移動方法... ...
  • 如果在應用中,如果想要給app 添加模糊濾鏡,可能第一想到的是第三方類庫,比如 Win2d、lumia Imaging SDK 、WriteableBitmapEx,不可否認,這些類庫功能強大,效果也挺多的。不足就是增加了生成包尺寸,由於增加了相應 dll 的引用,在 app運行時也會增加記憶體占用。 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...