I am working with files on C# and I got to a point where I don’t know how to continue anymore.
The scenario is this: If I upload 3 or more files with the same name at the same time, I want to handle them and change their name to from "myfile.pdf" to "myfile.pdf(1)/(2)/(3)…" depending on how much files I upload.
This is what I have tried so far and in this case, this only works for only the second file because when the third one comes, it will check there is any file with the same – yes, okay name it "myfile.pdf(2) – but this exists too so it will go to another place.
How can I achieve having the same three files in the same folder with this naming convention?
Here’s what I have tried so far:
string FileName = "MyFile.pdf";
string path = @"C:ProjectMyPdfFiles"
if (File.Exists(path))
{
int i = 1;
var FileExists = false;
while (FileExists==false)
{
if (FileExists == false)
{
FileName = FileName + "(" + i + ")";
}
else
return;
i++;
}
}
And the result of this code is: "MyFile.pdf", "MyFile.pdf(1)" And the third one doesn’t load here.
I think I’m missing something in the loop or idk :(.
Can someone help me?
I have tried also this:
if(File.Exists(path) || File.Exists(path+"(")
//because when the second file its uploaded, its name will be SecondFile.pdf(1), so this will return true and will proceed running, but still the iteration will "always" start from 0 since everytime I upload a file, I have to refresh the process.
3
Answers
This should do the job.
Don’t use return inside your while loop, better set ‘FileExists = true’ whenever you want you loop to stop. A return statement will exit your current method.
I think your problem can be easily solved using recursion, something like this (untested):
What this does is: it
CheckFileName
method will keep calling itself until it finds a name that doesn’t exist yet.I solved this by creating new folders with special names using the code below:
So what this does is that it will count how many files we have in that folder with the same name, so I have to check if we have more than 1 file, then change it’s name to file(1).
Thank you to everyone that tried to help me, much appreciated.