Click here to Skip to main content
Click here to Skip to main content

Console App in C# to rename files in a directory

, 18 Mar 2004
Rate this:
Please Sign up or sign in to vote.
Console App in C# to rename files in a directory

Introduction

This is a simple console program that batch renames files in a directory. There are some command line switches:

//  
//  --dir=c:/images/  
//      Operate  on  specified  directory
//
//  --prepend=text
//      Rename  file  by  prepending  specified  
//      text.    If  not  specified,  
//      the  app  will  prepend  a  random  number  
//      from  0  to  100000.    
//      This  is  typically  sufficient;  
//      if  there  is  a  collision  it  will  
//      log  a  warning.  
//
//  --pattern=*.jpg
//      Only  operate  on  files  matching  specified  pattern  

Code Listing

using  System;  
using  System.Collections;  
using  System.IO;  


namespace  Renamer
{
  
  public  class  RenameArgKeys
  {
    protected  RenameArgKeys()  {  }

    public  const  string  dir  =  "--dir";
    public  const  string  prepend  =  "--prepend";
    public  const  string  pattern  =  "--pattern";


  }


  public  class  Rename
  {
    protected  string[]  _args  =  null;
    public  Rename(string[]  args)
    {
      try
      {
        _args  =  args;  
        ParseArgs();  
      }
      catch(Exception  e)
      {
        Diag.LogException(e);
      }    
    }

    protected  Hashtable  _hash  =  null;  
    protected  Hashtable  Hash  
    {
      get
      {
        if  (_hash  ==  null)
        {
          _hash  =  new  Hashtable();  
        }
        return  _hash;  
      }
    }



    protected  void  ParseArgs()
    {
      try
      {
        if  ((_args  ==  null)  ||  (_args.Length  <  1))  return;
        foreach  (string  arg  in  _args)
        {
          char[]  sep  =  {  '='  };  
          string[]  keyval  =  arg.Split(sep,  2);  
          if  ((keyval  ==  null)  ||  (keyval.Length  <  1))  continue;

          string  key  =  keyval[0];
          string  val  =  "";  
          if  (keyval.Length  >=  2)  val  =  keyval[1];

          if  (Hash.ContainsKey(key))
          {
            Hash.Remove(key);  
          }

          Hash.Add(key,  val);  
        }
      }
      catch(Exception  e)
      {
        Diag.LogException(e);
      }


    }


    protected  string  SearchPattern
    {
      get
      {
        if  (!(Hash.Contains(RenameArgKeys.pattern)))
          return  "*.*";  

        return  Hash[RenameArgKeys.pattern]  as  string;  
      }
    }

    protected  string  Dir  
    {
      get
      {
        if  (!(Hash.Contains(RenameArgKeys.dir)))
          return  Directory.GetCurrentDirectory();  

        return  Hash[RenameArgKeys.dir]  as  string;  
      }
    }

    
    protected  Random  _rand  =  null;  
    protected  Random  Random
    {
      get
      {
        if  (_rand  ==  null)
        {
          _rand  =  new  Random();
        }
        return  _rand;  
      }
    }

    protected  const  int  _max_rand  =  100000;  

    protected  string  DefaultPrepend
    {
      get
      {
        string  num  =  Random.Next(_max_rand).ToString();          
        string  built  =  num  +  "_";  
        return  built;  
      }
    }


    protected  string  Prepend  
    {
      get
      {
        if  (!(Hash.Contains(RenameArgKeys.prepend)))
          return  DefaultPrepend;  

        return  Hash[RenameArgKeys.prepend]  as  string;  
      }
    }

    protected  string  GenDestName(string  source)
    {
      try
      {
        string  dir  =  Path.GetDirectoryName(source);  
        string  source_fname  =  Path.GetFileName(source);  

        string  targ_fname  =  Prepend  +  source_fname;  
        string  target  =  Path.Combine(dir,  targ_fname);  

        return  target;        
      }
      catch(Exception  e)
      {
        Diag.LogException(e);
        return  null;
      }

    }


    public  void  RenameIt(string  source)
    {
      try
      {
        if  (!(File.Exists(source)))  return;
  
        string  dest  =  GenDestName(source);  

        if  (File.Exists(dest))
        {
          Console.WriteLine("Cannot  rename  "  +  source  +  "  to  "  + 
             dest  +  ":    Destination  file  exists");  
          return;  
        }
        
        File.Move(source,  dest);  

      }
      catch(Exception  e)
      {
        Diag.LogException(e);
      }
    }

    public  void  Go()
    {
      try
      {
        string[]  files  =  Directory.GetFiles(Dir,  SearchPattern);  
        if  ((files  ==  null)  ||  (files.Length  <  1))  return;

        foreach(string  file  in  files)
        {
          RenameIt(file);  
        }
      }
      catch(Exception  e)
      {
        Diag.LogException(e);        
      }
    }

  }


  public  class  Diag
  {
    protected  Diag()  {}  
  
    public  static  void  LogException  (Exception  e)
    {
      if  (e  ==  null)  return;  
      string  msg  =  e.Message;  
      Console.WriteLine(msg);  
    }

  }


  class  EntryPoint
  {
    ///  <summary>
    ///  The  main  entry  point  for  the  application.
    ///  </summary>
    [STAThread]
    static  void  Main(string[]  args)
    {
      try
      {
        Rename  rename  =  new  Rename(args);  
        rename.Go();  
      }
      catch(Exception  e)
      {
        Diag.LogException(e);
      }
    }
  }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Per R. Anderson
Web Developer
United States United States
Per Anderson is the founder of Sunfrog Technologies LLC, http://sunfrog-tech.com .

Comments and Discussions

 
QuestionWhat if File.Move doesn't work as expected? Pinsussdbdannydb4-Oct-04 12:25 
AnswerRe: What if File.Move doesn't work as expected? PinsussAnonymous3-Dec-04 7:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 19 Mar 2004
Article Copyright 2004 by Per R. Anderson
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid