I have an application that loops through files and moves them to their respective folder. if a file already exists in a folder, I need to append a letter to the filename:

myfilehere.txt will become
myfilehere_a.txt

and if it comes in again, myfilehere_b.txt

the error is on the increment. nothing goes past 'a'. i have tried all types of loops. below is a portion of the code I am having problems.

thanks in advance.

char letter = Char.Parse("a");
            char letterEnd = Char.Parse("z");

            for (char i = letter; i < letterEnd; i++)
            {         

            //while (i<26)
            //{
                newfile = fname + "_" + letter.ToString() + extension;
                if (!File.Exists(dupePathDir))
                {
                    if (File.Exists(newfile))
                    {
                        
                        string whatfile = fname + "_" + i.ToString() +extension;
                        return whatfile;
                    }
                    else
                    {
                        return newfile;

                    }
                }
            }
            return null;
char letter = Char.Parse("a");
char letterEnd = Char.Parse("z");
if (File.Exists(dupePathDir))
{
    newfile = fname + extension; // set newfile initial value to match original filename
    while (File.Exists(newfile)) // loop while newfile exists in directory
    {
        for (char i = letter; i < letterEnd; i++)
        {
            int appended = fname.IndexOf("_" + i.ToString()); // obtain first indexed position of _letter in the file name, gets -1 if none
            if ((appended != -1) //Determine if the file name contains "_a" or whichever letter is currently represented by variable "i"
            {
                fname = fname.remove(appended) + "_" + (i+1).ToString(); // remove current _letter and add next one up in it's place
                newfile = fname + extension; // add the extension and compare in (File.Exists(newfile)) to continue or break loop
            }
            else
            {
                fname = fname + "_" + i.ToString(); //add _letter
                newfile = fname + extension; // add the extension and compare in (File.Exists(newfile)) to continue or break loop
            }
        }
    }
}

I believe that this loop might better serve your needs. I assumed here that all of your specific variables have been declared elsewhere in your code (ie: fname, extension, etc).

Hope this helps, I really didn't take the time to set up a file reader and such to test it but the loop SHOULD get you to the right place.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.