栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#实现的文件批量重命名功能示例

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#实现的文件批量重命名功能示例

本文实例讲述了C#实现的文件批量重命名功能。分享给大家供大家参考,具体如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//C#批量重命名文件代码的实现
//添加文件操作空间引用
using System.IO;
namespace WindowsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    private void button1_Click(object sender, EventArgs e)
    {
      FolderBrowserDialog f1 = new FolderBrowserDialog();
if (f1.ShowDialog() == DialogResult.OK)
      {
 textBox3.Text = f1.SelectedPath;
}
    }
    private void button2_Click(object sender, EventArgs e)
    {
     if (textBox3.Text!=""){
      if(textBox1.Text!="")
      {
string strOldFileName;
string strNewFileName;
string strOldPart = this.textBox1.Text.Trim();
string strNewPart = this.textBox2.Text.Trim();
string strNewFilePath;
string strFileFolder;
int TotalFiles = 0;
DateTime StartTime = DateTime.Now;//获取开始时间
try{
DirectoryInfo di = new DirectoryInfo(textBox3.Text);
FileInfo[] filelist = di.GetFiles("*.*");
strFileFolder = textBox3.Text;
int i = 0;
 foreach (FileInfo fi in filelist)
 {
   strOldFileName = fi.Name;
   strNewFileName = fi.Name.Replace(strOldPart, strNewPart);
   strNewFilePath = @strFileFolder + "\" + strNewFileName;
   filelist[i].MoveTo(@strNewFilePath);
   TotalFiles += 1;
   this.listBox1.Items.Add("文件名:" + strOldFileName + "  已重命名为 " + strNewFileName + "");
   i += 1;
      }
      DateTime EndTime = DateTime.Now;//获取结束时间
      TimeSpan ts = EndTime - StartTime;
      this.listBox1.Items.Add("总耗时:" + ts.Hours.ToString() + "时" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒"+ ts.Milliseconds.ToString()+"毫秒");
      }
      catch
      {
      MessageBox.Show("路径无效!");
      }
      }
 else
 {
 MessageBox.Show("没有匹配字符");
 }
      }
      else
      {
 MessageBox.Show("请先择择路径!");
      }
    }
  }
}

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#文件操作常用技巧汇总》、《C#遍历算法与技巧总结》、《C#程序设计之线程使用技巧总结》、《C#操作Excel技巧总结》、《C#中XML文件操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》

希望本文所述对大家C#程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/123345.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号