I needed a utility function/method that would get the next available filename to save as.
An example would be, if I need to save a file as MyTestFile.html but it already exists.
This method would then check to see what the next availble filename would be, and it would return
MyTestFile2.html
. If MyTestFile2.html
exists, then it would return MyTestFile3.html
, and so on.
I wrote the method, but it feels sloppy, and isn't really very elegant.
Any ideas for improving the readability of this code, or a better way to do it?
public string GetNextAvailableName(List<string> files, string baseFile)
{
var baseFileWithoutExt = Path.GetFileNameWithoutExtension(baseFile);
var baseExt = Path.GetExtension(baseFile);
//clean files and get the ones containing oure baseFileName
var cleanFiles = files
.Select(i => Path.GetFileNameWithoutExtension(i.ToLower()))
.Where(i => i.Contains(baseFileWithoutExt.ToLower()));
var count = cleanFiles.Count();
if (count == 0)
return baseFile;
int indexCount = 1;
do
{
indexCount++;
} while (cleanFiles.Contains(baseFileWithoutExt.ToLower() + indexCount));
return baseFileWithoutExt + indexCount + baseExt;
}
This would then be called like this:
GetNextAvailableName(Directory.GetFiles("C:\\MyFiles\\", "MyTestFile.html");
Then if MyTestFile.html
is already in use, it will return MyTestFileX.html
, where X
is the lowest positive integer where the filename doesn't exist yet.
files
? \$\endgroup\$ – svick Oct 6 '13 at 9:57