Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to add (#) to a filename when you find a duplicate filename?

I'm outputting files in C# and want to handle files being saved with the same name by adding brackets and a number:

FooBar.xml
FooBar(1).xml
FooBar(2).xml
...
FooBar(N).xml

Is there a simple way to do that in .NET? And is there a special name for the (#) construct?

like image 929
Gavin Miller Avatar asked Jul 23 '09 21:07

Gavin Miller


2 Answers

You'll just have to count up and manipulate the file names manually. The (pseudo)code below is dirty, but it's the basic algorithm. Refactor it to your needs.

var filenameFormat = "FooBar{0}.xml";
var filename = string.Format(filenameFormat, "");
int i = 1;
while(File.Exists(filename))
    filename = string.Format(filenameFormat, "(" + (i++) + ")");

return filename;

If you can get away with it, you could always just tack on DateTime.Now in a format of your choice. That's what we do for temporary files, anyway.

like image 142
Samantha Branham Avatar answered Oct 14 '22 00:10

Samantha Branham


In the end I utilized the accepted answer to create an extension method that looks like this:

public static string GetNextFilename(this string filename)
{
    int i = 1;
    string dir = Path.GetDirectoryName(filename);
    string file = Path.GetFileNameWithoutExtension(filename) + "{0}";
    string extension = Path.GetExtension(filename);

    while (File.Exists(filename))
        filename = Path.Combine(dir, string.Format(file, "(" + i++ + ")") + extension);

    return filename;
}
like image 34
Gavin Miller Avatar answered Oct 14 '22 01:10

Gavin Miller