欢迎来到虫虫下载站 | 资源下载 资源专辑 关于我们
虫虫下载站

form1.cs

可通过正则表达式进行无限级别的批量文本内容替换
CS
字号:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace TxtReplace
{
	/// <summary>
	/// Form1 的摘要说明。
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox txtPath;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtExp;
		private System.Windows.Forms.Button btnBrw;
		private System.Windows.Forms.Button btnReplace;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.ColumnHeader FileName;
		private System.Windows.Forms.ListView lstResult;
		private System.Windows.Forms.TextBox txtFileType;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.CheckBox chkSubDir;
		private System.Windows.Forms.CheckBox chkIsBak;
		private System.Windows.Forms.TextBox txtRep;
		private System.Windows.Forms.ColumnHeader num;
		private System.Windows.Forms.Button btnExp;
		/// <summary>
		/// 必需的设计器变量。
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Windows 窗体设计器支持所必需的
			//
			InitializeComponent();

			//
			// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
			//
		}

		/// <summary>
		/// 清理所有正在使用的资源。
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows 窗体设计器生成的代码
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.txtPath = new System.Windows.Forms.TextBox();
			this.chkSubDir = new System.Windows.Forms.CheckBox();
			this.label2 = new System.Windows.Forms.Label();
			this.txtExp = new System.Windows.Forms.TextBox();
			this.btnBrw = new System.Windows.Forms.Button();
			this.btnReplace = new System.Windows.Forms.Button();
			this.txtRep = new System.Windows.Forms.TextBox();
			this.label3 = new System.Windows.Forms.Label();
			this.chkIsBak = new System.Windows.Forms.CheckBox();
			this.label4 = new System.Windows.Forms.Label();
			this.lstResult = new System.Windows.Forms.ListView();
			this.FileName = new System.Windows.Forms.ColumnHeader();
			this.num = new System.Windows.Forms.ColumnHeader();
			this.txtFileType = new System.Windows.Forms.TextBox();
			this.label5 = new System.Windows.Forms.Label();
			this.btnExp = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.AutoSize = true;
			this.label1.Location = new System.Drawing.Point(16, 24);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(29, 17);
			this.label1.TabIndex = 0;
			this.label1.Text = "目录";
			// 
			// txtPath
			// 
			this.txtPath.Location = new System.Drawing.Point(80, 24);
			this.txtPath.Name = "txtPath";
			this.txtPath.Size = new System.Drawing.Size(360, 21);
			this.txtPath.TabIndex = 1;
			this.txtPath.Text = "";
			// 
			// chkSubDir
			// 
			this.chkSubDir.Location = new System.Drawing.Point(360, 56);
			this.chkSubDir.Name = "chkSubDir";
			this.chkSubDir.TabIndex = 2;
			this.chkSubDir.Text = "包含子目录";
			// 
			// label2
			// 
			this.label2.AutoSize = true;
			this.label2.Location = new System.Drawing.Point(16, 88);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(66, 17);
			this.label2.TabIndex = 3;
			this.label2.Text = "正则表达式";
			// 
			// txtExp
			// 
			this.txtExp.Location = new System.Drawing.Point(16, 112);
			this.txtExp.Multiline = true;
			this.txtExp.Name = "txtExp";
			this.txtExp.Size = new System.Drawing.Size(424, 80);
			this.txtExp.TabIndex = 4;
			this.txtExp.Text = "";
			// 
			// btnBrw
			// 
			this.btnBrw.Location = new System.Drawing.Point(448, 24);
			this.btnBrw.Name = "btnBrw";
			this.btnBrw.TabIndex = 5;
			this.btnBrw.Text = "浏览";
			this.btnBrw.Click += new System.EventHandler(this.btnBrw_Click);
			// 
			// btnReplace
			// 
			this.btnReplace.Location = new System.Drawing.Point(448, 224);
			this.btnReplace.Name = "btnReplace";
			this.btnReplace.TabIndex = 6;
			this.btnReplace.Text = "替换";
			this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click);
			// 
			// txtRep
			// 
			this.txtRep.Location = new System.Drawing.Point(16, 224);
			this.txtRep.Multiline = true;
			this.txtRep.Name = "txtRep";
			this.txtRep.Size = new System.Drawing.Size(424, 80);
			this.txtRep.TabIndex = 8;
			this.txtRep.Text = "";
			// 
			// label3
			// 
			this.label3.AutoSize = true;
			this.label3.Location = new System.Drawing.Point(16, 200);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(29, 17);
			this.label3.TabIndex = 7;
			this.label3.Text = "替换";
			// 
			// chkIsBak
			// 
			this.chkIsBak.Location = new System.Drawing.Point(224, 56);
			this.chkIsBak.Name = "chkIsBak";
			this.chkIsBak.Size = new System.Drawing.Size(128, 24);
			this.chkIsBak.TabIndex = 9;
			this.chkIsBak.Text = "是否备份原文件";
			// 
			// label4
			// 
			this.label4.AutoSize = true;
			this.label4.Location = new System.Drawing.Point(16, 328);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(54, 17);
			this.label4.TabIndex = 10;
			this.label4.Text = "替换结果";
			// 
			// lstResult
			// 
			this.lstResult.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																						this.FileName,
																						this.num});
			this.lstResult.GridLines = true;
			this.lstResult.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
			this.lstResult.HideSelection = false;
			this.lstResult.Location = new System.Drawing.Point(16, 352);
			this.lstResult.Name = "lstResult";
			this.lstResult.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
			this.lstResult.Size = new System.Drawing.Size(424, 97);
			this.lstResult.TabIndex = 11;
			this.lstResult.View = System.Windows.Forms.View.Details;
			// 
			// FileName
			// 
			this.FileName.Text = "文件名";
			this.FileName.Width = 300;
			// 
			// num
			// 
			this.num.Text = "替换数量";
			this.num.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
			// 
			// txtFileType
			// 
			this.txtFileType.Location = new System.Drawing.Point(80, 56);
			this.txtFileType.Name = "txtFileType";
			this.txtFileType.Size = new System.Drawing.Size(128, 21);
			this.txtFileType.TabIndex = 12;
			this.txtFileType.Text = "*.txt";
			// 
			// label5
			// 
			this.label5.AutoSize = true;
			this.label5.Location = new System.Drawing.Point(16, 56);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(54, 17);
			this.label5.TabIndex = 13;
			this.label5.Text = "文件类型";
			// 
			// btnExp
			// 
			this.btnExp.Location = new System.Drawing.Point(448, 112);
			this.btnExp.Name = "btnExp";
			this.btnExp.TabIndex = 14;
			this.btnExp.Text = "验证";
			this.btnExp.Click += new System.EventHandler(this.btnExp_Click);
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
			this.ClientSize = new System.Drawing.Size(544, 494);
			this.Controls.Add(this.btnExp);
			this.Controls.Add(this.label5);
			this.Controls.Add(this.txtFileType);
			this.Controls.Add(this.lstResult);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.chkIsBak);
			this.Controls.Add(this.txtRep);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.btnReplace);
			this.Controls.Add(this.btnBrw);
			this.Controls.Add(this.txtExp);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.chkSubDir);
			this.Controls.Add(this.txtPath);
			this.Controls.Add(this.label1);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			this.Name = "Form1";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "文本替换工具";
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void btnBrw_Click(object sender, System.EventArgs e)
		{
			FolderBrowserDialog frm = new FolderBrowserDialog();
			if(frm.ShowDialog()==DialogResult.OK)
			{
				this.txtPath.Text = frm.SelectedPath.ToString();
			}
		}

		private void btnReplace_Click(object sender, System.EventArgs e)
		{
			if(this.txtPath.Text =="")
			{
				MessageBox.Show("请选择目录!");
				return;
			}
			if(this.txtExp.Text  =="")
			{
				MessageBox.Show("请设置替换对象表达式!");
				return;
			}
			if(this.txtFileType.Text  =="")
			{
				MessageBox.Show("请设置文件类型!");
				return;
			}
			bool IsSubDir = false;
			if(this.chkSubDir.Checked)
			{
				IsSubDir = true;
			}
			bool IsBak = false;
			if(this.chkIsBak.Checked)
			{
				IsBak = true;
			}

			string strPath = this.txtPath.Text;
			string strExp = this.txtExp.Text;
			string strRep = this.txtRep.Text;
			string strFileType = this.txtFileType.Text;
			try
			{
				this.lstResult.Items.Clear();
				travelreplace(strPath, strRep, strExp,strFileType ,IsBak, IsSubDir);
				MessageBox.Show("替换完成!");

			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message.ToString());
			}

		
		}

		/// <summary>


		/// 替换文件中字符


		/// </summary>


		/// <param name="filefullname">文件全名</param>


		/// <param name="replacedby">用于替换的字符串</param>


		/// <param name="findpattern">用于查找的字符串</param>


		/// <param name="isbackup">是否备份文件</param>


		private  void doreplace(string filefullname, string replacedby, string findpattern, bool isbackup)
		{


			string result = String.Empty;


			string inputtext =String.Empty;


			string replacement = replacedby;


			string pat = findpattern;


			Regex r = new Regex(pat,RegexOptions.IgnoreCase);
			try 
			{

				System.Text.Encoding CurCoding  = null;
				using (StreamReader sr = new StreamReader(filefullname)) 
				{
					CurCoding=sr.CurrentEncoding;
					inputtext = sr.ReadToEnd();
					
				}
				
				// compile the regular expression.
				if (r.IsMatch(inputtext)) 
				{

					string num = r.Matches(inputtext).Count.ToString();
					
					 if (isbackup == true)
						  try 
						  {
							
					       File.Copy(filefullname, filefullname + ".bak",true);
						  }
						  catch(System.IO.IOException ex)
						  {
							  File.Copy(filefullname, filefullname + ".bak", true);
							  MessageBox.Show(ex.Message.ToString());
						  }
				
					result = r.Replace(inputtext, replacement);      

				     // add some text to the file.
					using (StreamWriter sw = new StreamWriter(filefullname,false,CurCoding)) 
					{

						
						sw.Write(result);
					}
					string[] Rst = new string[]{filefullname,num};
					ListViewItem Lrst = new ListViewItem(Rst);
					this.lstResult.Items.Add(Lrst);
					
				}  
			} 
			catch (Exception e) 
			{
			 MessageBox.Show("the process failed: "+e.Message.ToString());          
			
			}
		}

  /// <summary>


  /// 遍历目录


  /// </summary>


  /// <param name="path">起始路径</param>


  /// <param name="replacedby">用于替换的字符串</param>


  /// <param name="findpattern">用于查找的字符串</param>


  /// <param name="isbackup">是否备份文件</param>


  /// <param name="isgetsubfloder">是否获取子文件夹</param>


public void travelreplace(string path, string replacedstr, string findpattern,string fileType ,bool isbackup, bool isgetsubfloder)
{
	Queue queue = new Queue();
	DirectoryInfo di = null;
	string subpath = String.Empty;
	string currentpath = String.Empty;
	FileSystemInfo[] dirs = null;
	queue.Enqueue(path);
	while (queue.Count > 0)
	{    
		currentpath = (string)queue.Dequeue();
		di = new DirectoryInfo(currentpath);
		//get files under current directiory 
		
		FileSystemInfo[] files = di.GetFiles(fileType);
		
		foreach (FileSystemInfo f in files)
		{
			doreplace(f.FullName, replacedstr, findpattern, isbackup);   

		}

		// get only subdirectories 
		if (isgetsubfloder == true)
		{     

			dirs = di.GetDirectories();
			foreach (FileSystemInfo d in dirs)
			{
				subpath = d.FullName;
				queue.Enqueue(subpath);
			}
		}

    }

 }

		private void btnExp_Click(object sender, System.EventArgs e)
		{
			Process  appStar = new  Process();
			appStar.StartInfo.FileName = Application.StartupPath+"\\"+"RegexTester.exe";
			appStar.StartInfo.CreateNoWindow = true;
			appStar.Start();
		}

		

}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -