见之前写的一篇文章,算是批量替换的方法封装好了,无奈控制台太不友好,所以抽空搞成了winform 的界面,看着简单,没成想搞了两个晚上多才弄好,小小东西费了不少winform 的开发功力
之前的文章链接:程序猿利器(一) 批量替换 为妹子写了个批量替换内容的代码,无奈友好性和可操作性太渣,能改的给改提示好看点,功能性就别动了
做成了分三步操作的小界面,窗体大小固定,不许拖动,自动添加多个查找替换框,还用了数据绑定,控制panel 的隐藏与显示.....,先看看使用截图
第一步将要批量查找替换的文件都放到 In 文件夹下面
第二步 输入 查找内容和替换内容,其中可以替换文件名字和添加多个 查找-替换 关键字,点击开始替换 完成替换
第三步 在Out文件里面生成批量替换过的文件
关键代码如下:
批量替换的业务实现类
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace ReplaceScript
{
public class ReplaceManager
{
public string InPath = Environment.CurrentDirectory + @"\In";
public string OutPath = Environment.CurrentDirectory + @"\Out";
public List<ReplaceKeyValue> ReplaceValueList { get; set; }
public string TargetFileName { get; set; }
public string ReplaceFileName { get; set; }
public bool IsReplaceFileName { get; set; }
/// <summary>
/// 替换
/// </summary>
/// <param name="targetKeyWord"></param>
/// <param name="ReplaceKeyWord"></param>
/// <param name="filePath"></param>
public static void ReplaceScript(List<ReplaceKeyValue> list, string filePath, string SavePath)
{
if (list == null || list.Count == 0)
return;
string content = "";
using (FileStream fs = File.OpenRead(filePath))
{
System.Text.Encoding encode = GetType(fs);
content = File.ReadAllText(filePath, encode);
}
//replace all
foreach (var item in list)
{
content = content.Replace(item.targetKeyWord, item.replaceKeyWord);
}
//save file
File.WriteAllText(SavePath, content, Encoding.Default);
}
/// <summary>
/// 获得替换列表
/// </summary>
/// <returns></returns>
public static List<ReplaceKeyValue> GetReplaceKeyValue()
{
Console.WriteLine("***************这是华丽的分割线*******************");
Console.WriteLine("步骤二: 输入文件内容中要替换的查找字符串和替换字符串,以=分割,左边表示要查找的内容,右边表示要替换为的内容 以回车结束输入");
List<ReplaceKeyValue> list = new List<ReplaceKeyValue>();
string _targetKeyWord = "";
while (_targetKeyWord != "*")
{
Console.WriteLine("请输入要查找的内容和替换为的内容用=号分割 并回车,或者输入一个*并回车结束输入");
var instr = Console.ReadLine();
if (instr == "*")
break;
var strArray = instr.Split('=');
if (strArray.Length < 2)
{
Console.WriteLine("刚输入的没=号,骗子啊");
continue;
}
list.Add(new ReplaceKeyValue { targetKeyWord = strArray[0], replaceKeyWord = strArray[1] });
}
Console.WriteLine("*******下面开始批量替换了,按任意按键开始************");
Console.ReadKey();
return list;
}
/// <summary>
/// 获得当前文件夹下的所有文件及其相关信息
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
public static List<string> GetAll(DirectoryInfo dir)//搜索文件夹中的文件
{
List<string> FileList = new List<string>();
FileInfo[] allFile = dir.GetFiles();
foreach (FileInfo file in allFile)
{
FileList.Add(file.FullName);
}
DirectoryInfo[] allDir = dir.GetDirectories();
foreach (DirectoryInfo d in allDir)
{
FileList.AddRange(GetAll(d));
}
return FileList;
}
/// <summary>
/// Get Files Encoding
/// </summary>
/// <param name="fs"></param>
/// <returns></returns>
private static System.Text.Encoding GetType(FileStream fs)
{
BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
byte[] ss = r.ReadBytes(4);
//编码类型 Coding=编码类型.ASCII;
if (ss[0] <= 0xEF)
{
if (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)
{
return System.Text.Encoding.UTF8;
}
else
if (ss[0] == 0xFE && ss[1] == 0xFF)
{
return System.Text.Encoding.BigEndianUnicode;
}
else
if (ss[0] == 0xFF && ss[1] == 0xFE)
{
return System.Text.Encoding.Unicode;
}
else
{
return System.Text.Encoding.Default;
}
}
else
{
return System.Text.Encoding.Default;
}
}
/// <summary>
/// 替换用
/// </summary>
public void Replace()
{
List<string> fileList = new List<string>();
DirectoryInfo dir = new DirectoryInfo(InPath);
fileList = ReplaceManager.GetAll(dir);
string SaveFilePath = "";
foreach (var file in fileList)
{
if (this.IsReplaceFileName == true)
{
SaveFilePath = OutPath + @"\" + Path.GetFileName(file).Replace(this.TargetFileName, this.ReplaceFileName);
}
else
SaveFilePath = OutPath + @"\" + Path.GetFileName(file);
ReplaceManager.ReplaceScript(this.ReplaceValueList, file, SaveFilePath);
}
}
}
/// <summary>
/// 替换的键值对
/// </summary>
public class ReplaceKeyValue
{
/// <summary>
/// 目标值
/// </summary>
public string targetKeyWord { get; set; }
/// <summary>
/// 替换值
/// </summary>
public string replaceKeyWord { get; set; }
}
}
界面代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace ReplaceForm
{
public partial class Form1 : Form
{
private int rows = 1; //get the contentpanel rows count
private ReplaceScript.ReplaceManager replaceMag;
public Form1()
{
InitializeComponent();
this.replaceMag = new ReplaceScript.ReplaceManager();
this.replaceMag.ReplaceValueList = new List<ReplaceScript.ReplaceKeyValue>();
this.plLeft.Dock = DockStyle.Fill;
this.plMiddle.Dock = DockStyle.None;
this.plRight.Dock = DockStyle.None;
this.plLeft.Visible = true;
this.plMiddle.Visible = false;
this.plRight.Visible = false;
this.btn2.Visible = false;
//data bind
ReplaceScript.ReplaceKeyValue replaceValue = new ReplaceScript.ReplaceKeyValue();
this.tbOldContent.DataBindings.Add("Text", replaceValue, "targetKeyWord"); // Data Binding
this.tbnewContent.DataBindings.Add("Text", replaceValue, "replaceKeyWord"); // Data Binding
this.CB_File.DataBindings.Add("Checked", this.replaceMag, "IsReplaceFileName"); //Data Binding
this.replaceMag.ReplaceValueList.Add(replaceValue);
}
private void CB_File_CheckedChanged(object sender, EventArgs e)
{
CheckBox box = sender as CheckBox;
if (box.Checked == true)
{
this.plFileName.Visible = true;
this.plContent.Visible = true;
// this.plFileName.Location = new Point(this.plContent.Location.X,this.plContent.Location.Y);
}
else
{
this.plContent.Visible = true;
this.plFileName.Visible = false;
// this.plContent.Location = new Point(this.plFileName.Location.X, this.plFileName.Location.Y);
}
}
private void CB_Content_CheckedChanged(object sender, EventArgs e)
{
CheckBox box = sender as CheckBox;
if (box.Checked == true)
{
this.plContent.Visible = true;
this.plFileName.Visible = true;
// this.plContent.Location = new Point(this.plFileName.Location.X, this.plFileName.Location.Y);
}
else
{
this.plFileName.Visible = true;
this.plContent.Visible = false;
// this.plFileName.Location = new Point(this.plContent.Location.X, this.plContent.Location.Y);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
ReplaceScript.ReplaceKeyValue replaceValue = new ReplaceScript.ReplaceKeyValue();
//label
Label label = new Label();
label.Text = this.lbContent.Text;
label.Location = new System.Drawing.Point(lbContent.Location.X,lbContent.Location.Y+25*rows);
label.Size = new System.Drawing.Size(lbContent.Size.Width,lbContent.Size.Height);
this.plContent.Controls.Add(label);
//textBox oldContent
TextBox textBoxOld = new TextBox();
textBoxOld.Location = new System.Drawing.Point(tbOldContent.Location.X, tbOldContent.Location.Y + 25 * rows);
textBoxOld.Size = new System.Drawing.Size(tbOldContent.Size.Width, tbOldContent.Size.Height);
textBoxOld.Name = tbOldContent.Name + rows.ToString();
textBoxOld.DataBindings.Add("Text", replaceValue, "targetKeyWord"); // Data Binding
this.plContent.Controls.Add(textBoxOld);
// label =>
Label labelReplace = new Label();
labelReplace.Text = this.label2.Text;
labelReplace.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
labelReplace.ForeColor = System.Drawing.Color.Lime;
labelReplace.Location = new System.Drawing.Point(label2.Location.X, label2.Location.Y + 25 * rows);
labelReplace.Size = new System.Drawing.Size(label2.Size.Width, label2.Size.Height);
this.plContent.Controls.Add(labelReplace);
//textBox newContent
TextBox textBoxNew = new TextBox();
textBoxNew.Location = new System.Drawing.Point(tbnewContent.Location.X, tbnewContent.Location.Y + 25 * rows);
textBoxNew.Size = new System.Drawing.Size(tbnewContent.Size.Width, tbnewContent.Size.Height);
textBoxNew.Name = tbnewContent.Name + rows.ToString();
textBoxNew.DataBindings.Add("Text", replaceValue, "replaceKeyWord"); // Data Binding
this.plContent.Controls.Add(textBoxNew);
//add replaceValue
this.replaceMag.ReplaceValueList.Add(replaceValue);
//label rows
//label
Label labelr = new Label();
labelr.Text = (rows+1).ToString();
labelr.AutoSize = true;
labelr.Location = new System.Drawing.Point(this.lbrows.Location.X, lbrows.Location.Y + 25 * rows);
labelr.Size = new System.Drawing.Size(lbrows.Size.Width, lbrows.Size.Height);
this.plContent.Controls.Add(labelr);
//move button location
this.btnAdd.Location = new System.Drawing.Point(btnAdd.Location.X, btnAdd.Location.Y + 25);
this.rows++;
//set plContent autoScroll
this.plContent.AutoScrollPosition = new System.Drawing.Point(this.plContent.AutoScrollPosition.X, this.btnAdd.Location.Y+25*rows);
}
private bool VerificationAndGetValues()
{
TextBox box;
int rows = 1;
if (this.replaceMag.IsReplaceFileName == true)
{
if (this.tbOldName.Text.Trim().Length == 0 || this.tbNewName.Text.Trim().Length == 0)
{
MessageBox.Show(string.Format("文件名查找或替换输入框不能为空!"));
return false;
}
this.replaceMag.TargetFileName = this.tbOldName.Text.Trim();
this.replaceMag.ReplaceFileName = this.tbnewContent.Text.Trim();
}
foreach (var item in this.plContent.Controls)
{
if (item.GetType().Equals(typeof(TextBox)))
{
box = item as TextBox;
if (box.Name.StartsWith(this.tbnewContent.Name))
{
if (box.Text.Length == 0)
{
int.TryParse(box.Name.Replace(this.tbnewContent.Name, string.Empty), out rows);
MessageBox.Show(string.Format("第{0}行替换内容输入框不能为空!", rows == 0 ? 1 : rows));
return false;
}
}
if (box.Name.StartsWith(this.tbOldContent.Name))
{
if (box.Text.Length == 0)
{
int.TryParse(box.Name.Replace(this.tbOldContent.Name, string.Empty), out rows); //First rows will get rows=0!
MessageBox.Show(string.Format("第{0}行查找内容输入框不能为空!", rows == 0 ? 1 : rows));
return false;
}
}
}
}
return true;
}
//private bool VerificationAndGetValues()
//{
// TextBox box;
// int rows = 1;
// this.replaceMag.ReplaceValueList.Clear();
// ReplaceScript.ReplaceKeyValue replaceValue = new ReplaceScript.ReplaceKeyValue();
// foreach (var item in this.plContent.Controls)
// {
// if (item.GetType().Equals(typeof(TextBox)))
// {
// box = item as TextBox;
// if (box.Name.StartsWith(this.tbnewContent.Name))
// {
// if (box.Text.Length == 0)
// {
// int.TryParse(box.Name.Replace(this.tbnewContent.Name, string.Empty), out rows);
// MessageBox.Show(string.Format("第{0}行替换内容输入框不能为空!", rows == 0 ? 1 : rows));
// return false;
// }
// else
// {
// replaceValue = new ReplaceScript.ReplaceKeyValue();
// this.replaceMag.ReplaceValueList.Add(replaceValue);
// this.replaceMag.ReplaceValueList[this.replaceMag.ReplaceValueList.Count - 1].replaceKeyWord = box.Text.Trim(); //a little dangerous
// }
// }
// if (box.Name.StartsWith(this.tbOldContent.Name))
// {
// if (box.Text.Length == 0)
// {
// int.TryParse(box.Name.Replace(this.tbOldContent.Name, string.Empty), out rows); //First rows will get rows=0!
// MessageBox.Show(string.Format("第{0}行查找内容输入框不能为空!", rows == 0 ? 1 : rows));
// return false;
// }
// else
// {
// replaceValue.targetKeyWord = box.Text.Trim();
// }
// }
// }
// }
// return true;
//}
private void tbOldName_TextChanged(object sender, EventArgs e)
{
}
private void tbNewName_TextChanged(object sender, EventArgs e)
{
}
private void btnReplace_Click(object sender, EventArgs e)
{
bool result = this.VerificationAndGetValues();
if (result == false)
{
this.btn3.Visible = false;
return;
}
this.replaceMag.Replace();
this.btn3.Visible = true;
this.btn3_Click(null,null);
}
private void btnIn_Click(object sender, EventArgs e)
{
if (Directory.Exists(this.replaceMag.InPath) == false)
Directory.CreateDirectory(this.replaceMag.InPath);
if (Directory.Exists(this.replaceMag.OutPath) == false)
Directory.CreateDirectory(this.replaceMag.OutPath);
System.Diagnostics.Process.Start(this.replaceMag.InPath);
}
private void btn1_Click(object sender, EventArgs e)
{
if (sender !=null&& Directory.Exists(this.replaceMag.InPath)&& Directory.GetFiles(this.replaceMag.InPath).Length == 0 )
{
MessageBox.Show(string.Format("请将要查找的文件拷贝到弹出的文件夹里面!"));
return;
}
this.plLeft.Dock = DockStyle.Fill;
this.plMiddle.Dock = DockStyle.None;
this.plRight.Dock = DockStyle.None;
this.plLeft.Visible = true;
this.plMiddle.Visible = false;
this.plRight.Visible = false;
this.btn2.Visible = true;
}
private void btn2_Click(object sender, EventArgs e)
{
this.plLeft.Dock = DockStyle.None;
this.plMiddle.Dock = DockStyle.Fill;
this.plRight.Dock = DockStyle.None;
this.plLeft.Visible = false;
this.plMiddle.Visible = true;
this.plRight.Visible = false;
//this.plContent.Visible = true;
}
private void btn3_Click(object sender, EventArgs e)
{
this.plLeft.Dock = DockStyle.None;
this.plMiddle.Dock = DockStyle.None;
this.plRight.Dock = DockStyle.Fill;
this.plLeft.Visible = false;
this.plMiddle.Visible = false;
this.plRight.Visible = true;
}
private void btnOut_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(this.replaceMag.OutPath);
}
}
}
源代码下载:
http://download.csdn.net/detail/asa_jim/8976485 新号 没分 收5分 不算过分吧