If what you are after is to get something like the following:
c:\myfolder\file.doc
c:\myfolder\file1.doc
c:\myfolder\file2.doc
then your logic needs quite a bit of work. First, break your problem down.
Step 1. Does the file already exist?
public string GetUniqueFilename(string file)
{
if (File.Exists(file))
{
}
return file;
}
The next stage is to split the file name, extension and path into their most basic parts:
string folder = Path.GetDirectoryName(file);
string fileName = Path.GetFileNameWithoutExtension(file);
string extension = Path.GetExtension(file);
What you now need to do is use a simple loop to iterate and create the new filename.
int fileCounter = 1;
while (File.Exists(file))
{
file = Path.Combine(folder, $"{fileName}{fileCounter}{extension}");
fileCounter++;
}
Now that loop will keep going until it finds a unique file name at which point it will finish. As an optimisation, you will probably notice that you can drop the original File.Exists check and leave this entirely down to the
while
loop.