基于Winform的.cs文件命名空间排序及注释批量处理工具

时间:2023-01-21 06:56:44

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

杂乱的命名空间:

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文件中命名空间排序及注释的工具。

基于Winform的.cs文件命名空间排序及注释批量处理工具

代码:

 private void buttonConfirm_Click(object sender, EventArgs e)
{
string strfilepath = textBoxFilePath.Text;
List<string> liststrdocuments = new List<string>();
progressBarFiles.Visible = true;
if (!string.IsNullOrWhiteSpace(textBoxFilePath.Text) && System.IO.Directory.Exists(textBoxFilePath.Text)) //判断路径是否为空或者是否存在
{
if (!string.IsNullOrWhiteSpace(textBoxNameSpace.Text))
{
string[] strdocuments = Directory.GetFiles(strfilepath, "*.cs",SearchOption.AllDirectories); //得到文件夹路径下的所有cs文件路径
if (strdocuments.Length == ) //判断文件夹中是否没有cs文件
{
progressBarFiles.Visible = false;
MessageBox.Show(Properties.Resources.StringFileExist);
}
else
{
foreach (string strdocu in strdocuments) //排除部分cs文件,其中obj文件夹下的cs文件直接忽略
{
if(boolMode==true)
{
if (!strdocu.Contains("AssemblyInfo") && !strdocu.Contains("Designer") && !strdocu.Contains("obj") && !strdocu.Contains("designer"))
{
liststrdocuments.Add(strdocu);
}
}
else
{
if(!strdocu.Contains("obj"))
{
liststrdocuments.Add(strdocu);
}
}
} for (int i = ; i < liststrdocuments.Count; i++) //改变文件只读属性
{
if (File.GetAttributes(liststrdocuments[i]).ToString().IndexOf("ReadOnly") != -)
{
File.SetAttributes(liststrdocuments[i], FileAttributes.Normal);
}
}
int intprogress = ;
progressBarFiles.Maximum = liststrdocuments.Count;
DataTable dt = new DataTable();
dt.Columns.Add((Properties.Resources.StringDatagridViewCellHeaderOne), typeof(string));
dt.Columns.Add((Properties.Resources.StringDatagridViewCellHeaderTwo), typeof(string));
string strupdatestatus = null; foreach (string Documentpath in liststrdocuments) //遍历每个路径
{
System.Text.Encoding fileEncoding = GetFileEncodeType(Documentpath); //获取该文件的编码格式
intprogress++;
progressBarFiles.Value = intprogress;
string namespacerest = null;
string strusingsystem = null;
string strusingAutodesk = null;
string strusingBIMCore = null;
string strusingrest = null;
string namespaceresult = string.Empty;
string textboxcopyright = textBoxNameSpace.Text; List<string> listtempline = new List<string>();
List<string> listnamespacerest = new List<string>();
List<string> namespacesurplus = new List<string>(); if (DocumentChanged(Documentpath) == false)
{
strupdatestatus = Properties.Resources.StringUpdateStatusOne;
dt=BuildDataTable(dt,Documentpath,strupdatestatus);
}
else
{
string[] lines = File.ReadAllLines(Documentpath); //根据路径,分行读取该文件
foreach (string line in lines)
{
if (line.StartsWith("using"))
{
listtempline.Add(line); //得到命名空间的行
}
else if (!string.IsNullOrWhiteSpace(line))
{
listnamespacerest.Add(line); //记录剩下的部分
}
strupdatestatus = Properties.Resources.StringUpdateStatusTwo;
} #region 对namespace中的多余部分进行处理,保留没有空行的部分
foreach (string line in listnamespacerest)
{
if (line.StartsWith("namespace") || line.StartsWith("["))
{
break;
}
else if (!string.IsNullOrWhiteSpace(line))
{
namespacesurplus.Add(line);
}
}
if (namespacesurplus.Count != )
{
for (int i = ; i < listnamespacerest.Count; i++)
{
for (int j = ; j < namespacesurplus.Count; j++)
{
if (namespacesurplus[j] == listnamespacerest[i])
{
listnamespacerest.RemoveAt(i);
}
}
}
}
foreach (string line in listnamespacerest)
{
namespacerest += line + "\r\n";
}
#endregion listtempline.Sort(delegate(string str1, string str2) //对命名空间进行排序
{
return Comparer<string>.Default.Compare(str1.Trim(';'), str2.Trim(';'));
}); foreach (string line in listtempline) //对命名空间行归类
{
if (line.StartsWith("using System"))
{
strusingsystem += line + "\r\n";
}
else if (line.StartsWith("using Autodesk"))
{
strusingAutodesk += line + "\r\n";
}
else if (line.StartsWith("using BIMCore"))
{
strusingBIMCore += line + "\r\n";
}
else
{
strusingrest += line + "\r\n";
}
}
string strusingAutodeskresult;
string strusingBIMCoreresult;
string strusingrestresult;
strusingAutodeskresult = strusingBIMCoreresult = strusingrestresult = string.Empty;
string strusingsystemresult = "// System namespaces" + "\r\n" + strusingsystem + "\r\n"; if (!string.IsNullOrWhiteSpace(strusingAutodesk))
{
strusingAutodeskresult = strusingAutodesk;
strusingAutodeskresult = "// Autodesk namespaces" + "\r\n" + strusingAutodesk + "\r\n";
}
if (!string.IsNullOrWhiteSpace(strusingBIMCore))
{
strusingBIMCoreresult = strusingBIMCore;
strusingBIMCoreresult = "// BIMCore namespaces" + "\r\n" + strusingBIMCore + "\r\n";
}
if (!string.IsNullOrWhiteSpace(strusingrest))
{
strusingrestresult = strusingrest;
strusingrestresult = "// My namespaces" + "\r\n" + strusingrestresult + "\r\n";
}
namespaceresult = textboxcopyright + "\r\n" + strusingsystemresult + //重写文件
strusingAutodeskresult + strusingBIMCoreresult + strusingrestresult + namespacerest;
File.WriteAllText(Documentpath, namespaceresult, fileEncoding); textboxcopyright = strusingsystem = strusingAutodesk = strusingBIMCore = strusingrest = namespacerest = string.Empty; //变量清空
dt=BuildDataTable(dt, Documentpath, strupdatestatus); } } #region 控件属性的设置
dataGridViewfiles.DataSource = dt; //datagridview的设置
dataGridViewfiles.AllowUserToAddRows = false;
dataGridViewfiles.RowHeadersVisible = false;
dataGridViewfiles.AllowUserToResizeColumns = false;
dataGridViewfiles.AllowUserToResizeRows = false;
dataGridViewfiles.Columns[].Width = Convert.ToInt32(Math.Ceiling(0.3 * Convert.ToDouble(dataGridViewfiles.Width))); //设定更新状态栏的列宽
dataGridViewfiles.Columns[].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //设定更新状态栏的字体居中
progressBarFiles.Visible = false;
#endregion
}
}
else
{
progressBarFiles.Visible = false;
MessageBox.Show(Properties.Resources.StringTextBoxCopyrightStauts);
}
}
else
{
progressBarFiles.Visible = false;
MessageBox.Show(Properties.Resources.StringTextBoxFileStatus);
}
}

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();
if(buffer[]>=0xEF)
{
if(buffer[]==0xEF && buffer[]==0xBB)
{
return System.Text.Encoding.UTF8;
}
else if(buffer[]==0xFE && buffer[]==0xFF)
{
return System.Text.Encoding.BigEndianUnicode;
}
else if(buffer[]==0xFF && buffer[]==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文本框内容相同。

 private bool DocumentChanged(string path)
{
bool boolWholeStatus = true;
bool boolStatus1 = false;
bool boolStatus2 = false;
string oralcopyright = string.Empty;
string txtnamspace = textBoxNameSpace.Text+"\r\n";
string[] lines = File.ReadAllLines(path); //根据路径,分行读取该文件 foreach (string line in lines)
{
if (line.StartsWith("// System namespaces") || line.StartsWith("// System Namespaces") || line.StartsWith("//System namespaces") ||
line.StartsWith("//System Namespaces"))
{
boolStatus2 = true;
break;
}
else if(!string.IsNullOrEmpty("line"))
{
oralcopyright += line + "\r\n";
}
}
if (txtnamspace.Equals(oralcopyright))
{
boolStatus1 = true;
} if (boolStatus1 == true && boolStatus2 == true)
{
boolWholeStatus = false;
}
return boolWholeStatus;
}

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;
}