File or Folder rename to lower case In C# using DirectoryInfo/FileInfo.MoveTo()

ahmadali shafiee picture ahmadali shafiee · Nov 16, 2011 · Viewed 7.6k times · Source

I have a program that renames files or folders to lower case names. I have written this code:

    private void Replace(string FolderLocation, string lastText, string NewText)
    {
        if (lastText == "")
        {
            lastText = " ";
        }
        if (NewText == "")
        {
            NewText = " ";
        }

        DirectoryInfo i = new DirectoryInfo(FolderLocation);
        string NewName = "";
        if (checkBox2.Checked)
        {
            if (i.Parent.FullName[i.Parent.FullName.Length - 1].ToString() != "\\") //For parents like E:/
            {
                NewName = i.Parent.FullName + "\\" + i.Name.Replace(lastText, NewText);
            }
            else
            {
                NewName = i.Parent.FullName + i.Name.Replace(lastText, NewText);
            }

                NewName = NewName.ToLower();


            if (NewName != i.FullName)
            {
                 i.MoveTo(NewName);
            }
            foreach (DirectoryInfo sd in i.GetDirectories())
            {
                Replace(sd.FullName, lastText, NewText);
            }
        }
        if (checkBox1.Checked)
        {
            foreach (FileInfo fi in i.GetFiles())
            {
                NewName = fi.Directory + "\\" + fi.Name.Replace(lastText, NewText);

                    NewName = NewName.ToLower();

                if (NewName != fi.FullName)
                {
                    fi.MoveTo(NewName);
                }
            }
        }
    }

But I get the following exception:

"Source and destination path must be different."

How can I solve this issue?

Answer

Oded picture Oded · Nov 16, 2011

Since Windows is case insensitive, as far as file names are concerned, you will need to rename the file to a temporary name then rename back with lowercase characters.