使用DirectoryInfo / FileInfo.MoveTo()在C#中将文件或文件夹重命名为小写

时间:2011-11-16 13:52:22

标签: c# c#-4.0 window .net

我有一个程序可以将文件或文件夹重命名为小写名称。

我写了这段代码:

    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);
                }
            }
        }
    }

但我得到一个例外:

  

“源和目标路径必须不同。”

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:4)

由于Windows不区分大小写,因此就文件名而言,您需要将文件重命名为临时名称,然后使用小写字符重命名。

答案 1 :(得分:2)

尽管Windows文件系统存储名称为case-senstivie,但它们在名称比较时表现为不区分大小写,因此您的重命名操作将无效...

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

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

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

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

答案 2 :(得分:1)

这有效:

File.Move(destinationFilePath, destinationFilePath);

答案 3 :(得分:0)

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