文件改名的C#实现
2024-07-21 02:18:20
供稿:网友
 
其实很简单了,不过这里还是说一下,希望能给和我一样的c#新手带来帮助
背景:本人很爱看动画片和漫画,近日下载了火影忍者的漫画,结果目录中的图片文件命名方式是1,2,.....,10,....99,100,这样在acdsee中观看的顺序就是1,10,100....不是按照数字的顺序,看起来比较郁闷。故此就动手写一个批量文件改名的小程序,把文件名补齐为3位,按照001,002,...,009,010,...这样的顺序。
涉及到的知识:string的函数;file和directory函数;environment和一些界面类
核心代码如下:十分简单
 // 清空log
 this.listboxlog.items.clear();
 // 获取当前路径下全部文件名
 string[] files = directory.getfiles(environment.currentdirectory);
 foreach(string filename in files)
 {
 // 最后一个"/"
 int lastpath = filename.lastindexof("//");
 // 最后一个"."
 int lastdot = filename.lastindexof(".");
 // 纯文件名字长度
 int length = lastdot-lastpath-1;
 // 文件目录字符串 xx/xx/xx/
 string beginpart = filename.substring(0, lastpath+1);
 // 纯文件名字
 string namenoext = filename.substring(lastpath+1, length);
 // 扩展名
 string ext = filename.substring(lastdot);
 
 if(length < 3)
 {
 // 补齐为3位,组成新的文件名
 string namenew;
 if(length == 1)
 namenew = "00" + namenoext;
 else
 namenew = "0" + namenoext;
 string fullnewname = beginpart + namenew + ext;
 // 改名
 file.move(filename, fullnewname);
 // log
 this.listboxlog.items.add(namenoext + "--->" + namenew);
 this.listboxlog.selectedindex = this.listboxlog.items.count - 1;
 }