C# 中的批量重命名程序






2.89/5 (13投票s)
重命名文件

引言
在这个项目中,你将熟悉 Random
和 Directory
和 File
类,以及一点 Thread
类的用法。
背景
有一些应用程序可以完成这项工作,例如 FileRen。
Using the Code
对于批量重命名,首先我们需要获取用户文件夹的名称。
private void ChooseFolder_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
SelectedPathText.Text = folderBrowserDialog1.SelectedPath;
}
}
其次,我们需要将上述文件夹中的所有文件名都获取出来。为此,我使用了 Thread
类。
private void rename_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure ?",
"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
Thread tr = new Thread(new ThreadStart(chnTarget));
tr.Start();
}
}
private void chnTarget()
{
this.Invoke(new ThreadStart(ChangeName));
}
然后我编写了 ChangeName
方法。
private void ChangeName()
{
Random rand = new Random(DateTime.Now.Second);
string folder_path = SelectedPathText.Text;
long progress_value = 0;
string new_filename = "";
cancel = false;
progressBar1.Value = 0;
try
{
string[] FullPathFileNames = System.IO.Directory.GetFiles(folder_path);
progressBar1.Maximum = FullPathFileNames.Length;
if (FullPathFileNames.Length == 0) throw new Exception("No File Found \n");
foreach (string filename in FullPathFileNames)
{
if (cancel) break;
progress_value++;
try
{
if (!radioRandom.Checked)
{
new_filename = folder_path + "\\" +
textBoxTemplate.Text +
progress_value +
Path.GetExtension(filename); //gets extension of a file
}
else
{
if (checkBoxOmitExtension.Checked)
new_filename = folder_path + "\\" + rand.Next();
else
new_filename = folder_path + "\\" + rand.Next() +
Path.GetExtension(filename);
}
File.Move(filename, new_filename);
Application.DoEvents();
}
catch (Exception)
{
Application.DoEvents();
}
progressBar1.Value = (int)progress_value;
progressBar1.Update();
}
SelectedPathText.Text = "Complete";
cancel = false;
}
catch (Exception ex)
{
SelectedPathText.Text = ex.Message;
}
}
就是这样。
历史
- 2008年7月30日:初始发布
- 2010年1月12日:修复了一个错误