当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

使用C#给文件批量重命名

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2018-12-31 11:14:19

:2010-05-06 19:43:00

其实搞这个小程序只是为了更好的解决现在遇到的问题,什么问题呢?现在在做关于图像处理的课题,用CCD批量拍摄了几百副图像,命名方式为1.bmp,2.bmp,3.bmp。。。 ,按顺序来的,因为有些图像因为模糊或者不符合处理条件,我手动将其剔除,于是有了刚才提到的问题,现在的大量图片文件名不连续了,用Matlab处理时不方便。于是写了个C#小程序用来自动排列图像。代码如下

  1 using System;
  2  using System.Collections.Generic;
  3 using System.Text;
  4 using System.IO;
  5 using System.Windows.Forms;
  6 // 自动重命名
  7 namespace renamebmp
  8 {
  9     class Program
  10     {
  11         static void Main(string[] args)
  12         {
  13             int first = 1;    //起始图片编号
  14             int last = 301; //结束图片编号
  15             int temp;
  16             string path1; //寻找到的第一个空位置
  17             string path2; //寻找到的空位置后的最小编号图片文件路径
  18             int count = 0;  //图片数量
  19             string temppath = "";
  20             for (int k = first; k <= last; k++)
  21             {
  22                 temppath = "F:\\test6\\" + k.ToString() + ".bmp";
  23                 if (File.Exists(temppath))
  24                     count++;
  25             }

  26             for (int i = first; i <= count; i++)
  27             {
  28                 temp = i + 1;
  29                 path1 = "F:\\test6\\" + i.ToString() + ".bmp";
  30                 if (!File.Exists(path1))
  31                 {
  32                     path2 = "F:\\test6\\" + temp.ToString() + ".bmp";
  33                     while (!File.Exists(path2))
  34                     {
  35                         temp++;
  36                         if (temp == last)
  37                         {
  38                             path2 = "F:\\test6\\" + last.ToString() + ".bmp";
  39                             break;
  40                         }

  41                         path2 = "F:\\test6\\" + temp.ToString() + ".bmp";
  42                     }

  43                     File.Move(path2, path1);  // 使用move方法重命名
  44                 }

  45             }

  46             MessageBox.Show("排序完毕,排序后图片数量为 "+count.ToString());
  47         }

  48     }

  49 }



使用C#给文件批量重命名