private static string GetUniqueFileName(string directory, string fileName, CodeLanguage language, bool overwrite)
{
// Get the appropriate file extension for the selected programming language.
string ext = CodeWriter.GetExtension(language);
// Read the file name without the extension.
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
// Construct the absolute path of the file by concatanating directory name, file name and the
// extension.
string absPath = Path.Combine(directory, string.Format("{0}.{1}", fileNameWithoutExt, ext));
// Can't we overwrite files?
if (!overwrite)
{
// We arrive here if we cannot overwrite existing files.
// Counter used for generating the numeric constant for unique file name generation.
int counter = 1;
// Create a new file name until the created file name does not exist in the file system.
while (File.Exists(absPath))
{
// Create the new file name.
absPath = Path.Combine(directory, string.Format("{0}{1}.{2}", fileNameWithoutExt, counter.ToString(), ext));
// Increment the counter.
counter++;
}
}
// Finally return the generated absolute path of the file.
return absPath;
}