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.