3

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?

4

4 回答 4

6

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.

于 2011-11-16T13:54:39.090 回答
2

尽管 Windows 文件系统存储名称区分大小写,但它们在名称比较时不区分大小写,因此您的重命名操作将不起作用......

如果您确实需要/想要这样做,您需要首先将文件/目录临时重命名为不同且独特的名称,然后将其“重新”重命名为您想要的“小写名称”。

有关参考,请参阅http://msdn.microsoft.com/en-us/library/ee681827%28v=vs.85%29.aspxhttp://support.microsoft.com/kb/100108/en-us

如果您需要 NTFS 区分大小写,您可以将ObCaseInsensitive下 的 dword 设置HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\kernel\为 0(不推荐!)。

如果您正在处理 NFS,请参阅http://technet.microsoft.com/en-us/library/cc783185%28WS.10%29.aspx

于 2011-11-16T13:55:32.213 回答
1

这有效:

File.Move(destinationFilePath, destinationFilePath);
于 2020-04-28T02:53:02.563 回答
0

不幸的是,这是一个 Windows 问题,因为 Oded 在评论中提到它不区分大小写。您需要做的是两次重命名文件夹。通过将文件夹移动到一个新的临时名称,然后回到原始名称的小写字母。

于 2011-11-16T13:56:02.740 回答