My C# code is generating several text files based on input and saving those in a folder. Also, I am assuming that the name of the text file will be same as input. (The input contains only letters)
If two files has same name then it is simply overwriting the previous file.
But I want to keep both files.
I don’t want to append current date time or a random number to the 2nd file name. Instead I want to do it the same way Windows does. If the first file name is AAA.txt then second file name is AAA(2).txt, third file name will be AAA(3).txt and …..N th file name will be AAA(N).txt.
string[] allFiles = Directory.GetFiles(folderPath)
.Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray();
foreach (var item in allFiles)
{
// newFileName is the txt file which is going to be saved in the provided folder
if (newFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
{
// What to do here ?
}
}
This will check for the existence of files with tempFileName and increment the number by one until it finds a name that does not exist in the directory.