Wanda Maximoff Wanda Maximoff - 2 months ago 12
C# Question

Incrementing file name goes on infinite loop logic error C#

I am trying to upload a file then copying that file and moving it to another folder named "Converted". If the file already exists in the Converted folder, the file name should increment. What I'm getting on my code is an infinite loop and doesn't stop until I stop my program.

E.g. Reflection Paper.docx

Code:

string myFile = fileDoc.Text; //C:\Users\Admin\Documents\ThesisSampleFolders\Original\Reflection Paper.docx
string targetPath2 = @"C:\Users\Admin\Documents\ThesisSampleFolders\Converted";
string result = Path.GetFileName(myFile);

string combinePath = System.IO.Path.Combine(targetPath2, result);

int count = 1;

string fileNameOnly = Path.GetFileNameWithoutExtension(combinePath);
string extension = Path.GetExtension(combinePath);
string path = Path.GetDirectoryName(combinePath);
string newFullPath = combinePath;
string tempFileName = "";

while (File.Exists(newFullPath))
{
tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
newFullPath = Path.Combine(path, tempFileName + extension);
File.Copy(myFile, newFullPath);
//break;
}


The thing is, I've tried to put
break
but what happens is that after it increments for the first time, an error appears saying Reflection Paper(1).docx already exists when it should become Reflection Paper(2).docx. I apologize for this. I really hope you can help me. Thank you so much for your help!

Answer

This should work:

do
{
    if (File.Exists(newFullPath)) // if file exists get a new file name
    {
        tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
        newFullPath = Path.Combine(path, tempFileName + extension);
    }
    else // copy with the new path
    {

        File.Copy(myFile, newFullPath);

        break;
    }
}
while (true);

Change to do { } while with a break condition.

Comments