星期六

批量替换文本文件中的字符

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using System.IO;
10 namespace ReplaceText
11 {
12     public partial class Form1 : Form
13     {
14         public Form1()
15         {
16             InitializeComponent();
17         }
18 
19         private void buttonRun_Click(object sender, EventArgs e)
20         {
21             int count = 0;
22             string patho = this.textBox1.Text;
23             string paths = this.textBox2.Text;
24             string newpath = "";
25             string log = "";
26             DirectoryInfo dir = new DirectoryInfo(patho);
27 
28             foreach (var f in dir.GetFiles("*.*", SearchOption.AllDirectories))
29             {
30                 if (this.ReadText(f.FullName).IndexOf(this.textBox3.Text) > -1)
31                 {
32                     count += 1;
33                     this.listBoxList.Items.Add(f.FullName);
34                     log += f.FullName + Environment.NewLine;
35                     newpath = f.FullName.Replace(this.textBox1.Text, this.textBox2.Text);
36                     Directory.CreateDirectory(Path.GetDirectoryName(newpath));
37                     File.Copy(f.FullName, newpath, true);
38                     Replace(newpath, this.textBox3.Text, this.textBox4.Text);
39                 }
40             }
41             this.labelMsg.Text = "替换了 " + count.ToString() + " 个文件";
42             log += this.labelMsg.Text;
43             using (StreamWriter sw = new StreamWriter("c:\\log.log"true, Encoding.GetEncoding("gb2312")))
44             {
45                 sw.Write(log);
46                 sw.Close();
47             }
48         }
49         private string ReadText(string path)
50         {
51             using (StreamReader sr = new StreamReader(path, Encoding.GetEncoding("gb2312")))
52             {
53                 return sr.ReadToEnd();
54             }
55         }
56         private void Replace(string path, string oldValue, string newValue)
57         {
58             string text = this.ReadText(path);
59             text = text.Replace(oldValue, newValue);
60             File.Delete(path);
61             using (StreamWriter sw = new StreamWriter(path, true, Encoding.GetEncoding("gb2312")))
62             {
63                 sw.Write(text);
64                 sw.Close();
65             }
66         }
67     }
68 }
69 

 

 

posted on 2010-08-10 15:47  星期六  阅读(509)  评论(0编辑  收藏  举报