I think you would have to do something along the lines of having a dictionary of file names, like this:
Dictionary<string, int> fileNameOccurences = new Dictionary<string, int>();
// ...
string fileName = "FooBar";
if ( fileNameOccurences.ContainsKey(fileName) ) {
fileNameOccurences[fileName]++;
fileName += "(" + fileNameOccurences[fileName].ToString() + ")";
}
else { fileNameOccurences.Add(fileName, 1); }
SaveFile(fileName + ".xml");
In this case, you may need to parse out the extension or refactor or something like that.
If you don't have control over the names of files in the directory, then you can count the occurences manually:
string fileName = "FooBar";
string[] fileNames = Directory.GetFiles(theDirectory, fileName + "*.xml");
fileName += "(" + (fileNames.Count + 1).ToString() + ")";
SaveFile(fileName + ".xml");
EDIT: As has been pointed out in the comments, this is a quick-and-dirty solution with a major bug.
Here's a slower (I imagine), but more robust solution:
string fileName = "FooBar", directory = @"C:\Output";
int no = 0;
while ( ++no > 0 && File.Exists(Path.Combine(directory, fileName + "(" + no.ToString() + ").xml")) );