工作的原因,要对大量的图片(主要是JPEG文件)进行重命名的处理。本人用C#编写了一个小程序,在这里和大家分享一下。也算是总结一下吧!
一、从Excel文件中读取数据
Excel文件中主要是一个学生的数据库,包含学生的姓名、性别、学号等信息,在本程序中,只需要将Excel文件中的序号和学号读入到程序中即可。代码如下:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
private void ConstructExcelDB(string fileName,int length)
{
string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(connStr);
OleDbCommand comm = new OleDbCommand();
comm.CommandText = "Select [序号],[学号] from [AllStudents$]";
comm.Connection = conn;
OleDbDataReader reader;
try
{
conn.Open();
reader = comm.ExecuteReader();
while (reader.Read())
{
if (!excels.ContainsKey(FormatStr((reader["序号"].ToString()).Trim(),length)))
{
excels.Add(FormatStr((reader["序号"].ToString()).Trim(),length), (reader["学号"].ToString()).Trim());
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString(), "Error");
}
}
private string FormatStr(string str,int length)
{
string temp = string.Empty;
for (int i = 0; i < length - str.Length; i++)
{
temp += "0";
}
return temp + str;
}
这里出现一个问题,就是从Excel文件中的Sheet1工作薄中的“序号”字段中读出的数据不能正确读取,如对于“0001”,它读取的结果为“1”,所以我使用了FormatStr()方法将格式化该字段中的数据。excels是一个私有成员,其声明代码为:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
private Dictionary<string, string> excels = new Dictionary<string, string>();
二、执行重命名操作
当单击“开始转换”按钮后,应用程序首先遍历你选择的目录,然后将JPEG文件的名字(开始时是以序号来命名的)转换为相对应的学号来命名。代码如下:
![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
private void RenameAllJPEGFiles(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
foreach (FileInfo fi in files)
{
if (fi.Extension == ".JPG")
{
Computer myCom = new Computer();
if (excels.ContainsKey(GetName(fi.Name)))
{
string str = excels[GetName(fi.Name)] + fi.Extension;
myCom.FileSystem.RenameFile(fi.FullName, str);
tbxDetails.AppendText(Environment.NewLine + fi.Name + " -----> " + str);
tbxDetails.ScrollToCaret();
jpegCount++;
}
}
}
foreach (DirectoryInfo di in dirs)
{
RenameAllJPEGFiles(di.FullName);
}
}
这样,所选目录中的所有JPEG文件就重命名成功了。
程序界面如下: