文件重命名并输出文件名列表

public partial class frmRename
: Form
{
List<string> ldir;
string lastPath;
public frmRename()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (!Directory.Exists(txtDir.Text.Trim()))
{
MessageBox.Show(string.Format("目录{0}不存在!",
txtDir.Text.Trim()));
return;
}
ldir = new List<string>();
FindAllFiles(txtDir.Text.Trim());
if (ldir.Count > 0)
{
List<string> listNew = new List<string>();
foreach (string s in ldir)
{
FileInfo fi = new FileInfo(s);
string newName = fi.Name;
if(txtOrig.Text!="")
{
//替换文件名
newName = newName.Replace(txtOrig.Text, txtNew.Text);
}
string newFileName = fi.DirectoryName + "\\" + newName;
listNew.Add(newName);
if (fi.FullName == newFileName)
{
continue;
}
fi.MoveTo(newFileName);
}
if (chckCreateFile.Checked && listNew.Count>0)
{
//生成文件列表
using (FileStream fs = new FileStream(txtDir.Text.Trim('\\') + "\\" +
"1.txt", FileMode.OpenOrCreate))
{
StreamWriter
sw = new StreamWriter(fs);
foreach (string s in listNew)
sw.WriteLine(s);
sw.Close();
fs.Close();
}
}
}
MessageBox.Show("处理完成!");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
private void FindAllFiles(string fileDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(fileDirectory);
FileSystemInfo[] fsi = diSource.GetFileSystemInfos();
FileInfo fi;
for (int i = 0; i < fsi.Length; i++)
{
//不是目录,查看文件属性;是目录,继续遍历。
if (Directory.Exists(fsi[i].FullName) == false)
{
fi = new FileInfo(fsi[i].FullName);
//判断文件类型,进行相应的后继操作。
if (txtExt.Text.Trim()=="" || (txtExt.Text.ToLower() +
".").Contains(fi.Extension.ToLower() + "."))
{
ldir.Add(fsi[i].FullName);
}
}
else
{//包含子文件夹
if (checkBox1.Checked) FindAllFiles(fsi[i].FullName);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1_open())
txtDir.Text = lastPath;
}
private bool folderBrowserDialog1_open()
{
//设置根在桌面
folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.Desktop;
//设置当前选择的路径
if (lastPath == null) lastPath = Environment.SpecialFolder.Desktop.ToString();
folderBrowserDialog1.SelectedPath = lastPath;
//允许在对话框中包括一个新建目录的按钮
folderBrowserDialog1.ShowNewFolderButton = true;
//设置对话框的说明信息
folderBrowserDialog1.Description = "请选择目录";
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
lastPath = folderBrowserDialog1.SelectedPath;
//在此添加代码,选择的路径为folderBrowserDialog1.SelectedPath
return true;
}
return false;
}
}

原文地址:https://www.cnblogs.com/dashi/p/4034653.html