文本替换小程序

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace replace
{
	class Program
	{
		static void Main(string[] args)
		{
			//创建日志文件
			string logpath = System.Environment.CurrentDirectory + "//log.txt";
			if (!File.Exists(logpath))
			File.Create(logpath);

			
			//开始替换
			try
			{				
					ReplaceFiles(System.Environment.CurrentDirectory + "//待替换");				
			}
			catch (Exception e)
			{
				System.Windows.Forms.MessageBox.Show("出错");
			}
		}


		/// 
		/// 批量替换文件文本
		/// 
		/// 
		public static void ReplaceFiles(string path)
		{
			string[] fs;
			string[] dirs;
			//是文件
			if (File.Exists(path))
			{
				ReplaceFile(path);
				return;
			}
			//是目录
			if (Directory.Exists(path))
			{
				fs = Directory.GetFiles(path);
				foreach (string f in fs)
				{
					ReplaceFile(f);
				}
				dirs = Directory.GetDirectories(path);
				foreach (string d in dirs)
				{
					ReplaceFiles(d);
				}
				
				return;
			}
		}



		/// 
		/// 替换单个文本文件中的文本
		/// 
		/// 
		/// 
		/// 
		/// 
		/// 
 
 
		public static bool ReplaceFile(string filename)
		{
			FileStream fs = File.OpenRead(filename);
			
			
			//判断文件是文本文件还二进制文件。该方法似乎不科学
			byte b;
			for (long i = 0; i < fs.Length; i++)
			{
				b = (byte)fs.ReadByte();
				if (b == 0)
				{
					System.Windows.Forms.MessageBox.Show(filename+"非文本文件");
					return false;//有此字节则表示改文件不是文本文件。就不用替换了
				}
			}

			//判断文本文件编码规则。
			byte[] bytes = new byte[2];
			Encoding coding = Encoding.Default;
			if (fs.Read(bytes, 0, 2) > 2)
			{
				if (bytes == new byte[2] { 0xFF, 0xFE }) coding = Encoding.Unicode;
				if (bytes == new byte[2] { 0xFE, 0xFF }) coding = Encoding.BigEndianUnicode;
				if (bytes == new byte[2] { 0xEF, 0xBB }) coding = Encoding.UTF8;
			}

			fs.Close();

			//获取替换规则
			DataSet ds = GetReplaceRule();

			//替换数据
			string[] lines = File.ReadAllLines(filename, coding);
			string logpath = System.Environment.CurrentDirectory + "//log.txt";

			string contents = "/r/n/r/n/r/n" + DateTime.Now.ToString() + "在:" + filename + "替换/r/n";
			//content+=lines[i]+" /n ";
			//  File.WriteAllText(logpath, "'"+ content, coding);
			File.AppendAllText(logpath, contents, coding);



			for (int i = 0; i < lines.Length; i++)
			{
				RegexOptions ops = RegexOptions.None;
				for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
				{
					string search = ds.Tables[0].Rows[j][1].ToString();
					string replace = ds.Tables[0].Rows[j][2].ToString();
					
					//todo 记录日志
					if(Regex.IsMatch(lines[i],search))
					{
						try
						{
			         //   string strOldText = File.ReadAllText(logpath, coding);
							string content = "第" + (i+1) + "行/t";
							content += lines[i] + " /t/t/t将 " + search+" 替换为 "+replace+ "/r/n";
                      //  File.WriteAllText(logpath, "'"+ content, coding);
                        File.AppendAllText(logpath, content, coding);
						}
						catch (Exception e3)
						{
							System.Windows.Forms.MessageBox.Show(e3.ToString());
						}
					}
					lines[i] = Regex.Replace(lines[i], search, replace);
				}
				
			}
			File.WriteAllLines(filename, lines,coding);
			return true;
		}



		/// 
		/// 读取替换规则文件
		/// 
		/// 
 
 
		public static  DataSet GetReplaceRule()
		{
			string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
               Data Source=" + System.Environment.CurrentDirectory + @"/替换规则/replace_rule.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
			DataSet ds = new DataSet();
			OleDbConnection con;
			OleDbDataAdapter myadapter;
			con = new OleDbConnection(connectionString);
			try 
			{
				con.Open();
				myadapter = new OleDbDataAdapter("select * from [Sheet1$]", con);
				myadapter.Fill(ds, "ds");
				myadapter.Dispose();
			}
			 catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
			{
                con.Close();
            } 
				return ds;
			}
	}
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值