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?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With