Wednesday, March 24, 2010

Generating incremental file name

Following code could help you in getting Incremental or Unique file name.

If file abc.txt already exist than following function will return abc1.txt, if abc1.txt exists than abc2.txt and so on.

public static string GetIncrementalFilename(string FileName)
{
int count = 0;
string Name = "";

if (System.IO.File.Exists(FileName))
{
System.IO.FileInfo f = new System.IO.FileInfo(FileName);
if (!string.IsNullOrEmpty(f.Extension))
{
Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
}
else
{
Name = f.FullName;
}

while (File.Exists(FileName))
{
count++;
FileName = Name + count.ToString() + f.Extension;
}
}
return FileName;
}

1 comment:

  1. Instead of using a loop, you can use Directory.GetFiles method to get the number of files already available. Also, this method does not ensure that the file name returned will be correct as the OS can create a file at any point and you might get a file name which is not unique. Also this method is not thread safe.

    ReplyDelete