日期:2013-04-30  浏览次数:20503 次

其实很简单了,不过这里还是说一下,希望能给和我一样的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;
}