Incremental Filenames

I was tinkering with a little program in C# this morning that needed to create incremental filenames instead of just overwriting the existing file.  As in: myfilename.htm -> myfilename_1.htm etc.

So here is the rough and ready version of what I did.

private string GetOutputFilename(string path,string filename,string extension)
{
     string[] files = Directory.GetFiles(path,filename+"*."+extension);
     if(files.Length==0) return path+"\\"+filename+"."+extension;
     return path+"\\"+filename+"_"+files.Length.ToString()+"."+extension;
}

It basically uses the filename+wildcard+extension to filter a directory listing.  If the listing is longer than zero it assumes that the next increment is going to be the number of files that are already there.

It’s a very simple algorithm that mostly works fine, but is not perfect.  Say you have the following files:

filename.htm
filename_1.htm
filename_2.htm
filename_3.htm

and you delete filename_2.htm.  This method will try to tell you that filename_3.htm is the next file – which is clearly wrong.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Add to favorites
  • email
  • FriendFeed
  • LinkedIn
  • NewsVine
  • Reddit
  • StumbleUpon
  • Tumblr
  • Twitter
  • Yahoo! Buzz
This entry was posted in Programs, how to and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">