小程式:FnameReviser

程式名稱:FnameReviser
程式功能:
將一群副檔名不符合的改唯一致化的副檔名,具有副檔名的就改掉副檔名,沒有副檔名的就直接加上副檔名。

參考資料:
Micorsoft MSDN2:類別庫參考

程式流程:
request User for 指定的目錄
if isExist & isDirectory = false then
 show error msg and  exist program.
 for each 檔案 in 指定的目錄
  origin_name <- the 'Name' of 檔案
  if subname of origin_name != JPG then
   new_name <- origin_name + '.JPG'
   if new_name is an exist file in the 指定的目錄 then
    new_name <- random generate a name
   rename from origin_name to new_name in the 指定的目錄
完成程式碼:
using System;
using System.IO;

class FnameReviser {
 public static string CONST_EXT_NAME = "jpg";
 public static string CONST_APPEND_EXTENSION = "." + CONST_EXT_NAME;
 public static int CONST_RAND_GEN_NAMELEN = 24;
 public static Random rand = new Random();


 public static void Main(String[] args) {
  string origin_name = null;
  string new_name = null;
  string work_dir = null;
  string[] fileInDir = null;

  // 要求使用者指定一個資料夾位置
  if (args.Length < 1) {
   Console.WriteLine("too few parameter.");
   return ;
  } else {
   work_dir = args[0];
  }

  try {
   // if isExist & isDirectory = false then
   if (Directory.Exists(work_dir) == false) {
   
    // Show error msg and exist program.
    Console.WriteLine("Error: {0} is not an exist the directory",work_dir);
    return;
   }

   // for each 檔案 in 指定的目錄
   fileInDir = Directory.GetFiles(work_dir);
   foreach ( string fname in fileInDir ) {

    // origin_name <- the 'Name' of 檔案
    origin_name = fname;

    // if subname of origin_name != JPG then
    int subname_indx = origin_name.LastIndexOf(".");
    if (origin_name.Substring(subname_indx+1) != CONST_EXT_NAME) {
    
     // new_name <- origin_name + '.JPG'
     if (subname_indx == -1)
      new_name = String.Concat(origin_name ,CONST_APPEND_EXTENSION);
     else
      new_name = String.Concat(origin_name.Substring(0,subname_indx) ,CONST_APPEND_EXTENSION);
     
     // if new_name is an exist file in the 指定的目錄 then
     while (File.Exists(new_name)) {
     
      // new_name <- random generate a name
      new_name = String.Concat(genFileName() ,CONST_APPEND_EXTENSION);
     }
    }
    
    // rename from origin_name to new_name in the 指定的目錄
    Console.WriteLine("{0} rename to {1}." ,origin_name ,new_name);
    File.Move (origin_name ,new_name);
   }
   Console.WriteLine("File Revise End.");
  }
  catch (Exception e) {
   Console.WriteLine("Error occur :{0} ", e.ToString());
  }
 }
 
 public static string genFileName() {
  string name = "";
  for (int i=0 ; i<CONST_RAND_GEN_NAMELEN ; i++)
   name += (rand.Next()%10);
  return name;
 }
}


未來可增加的功能:

  • 依照MIME type 的檔案類型判定,再決定這個檔案的副檔名
  • 批次化修改檔名
  • 程式GUI化

留言