文件或文件夹重命名为小写在C#中使用DirectoryInfo / FileInfo.MoveTo() [英] File or Folder rename to lower case In C# using DirectoryInfo/FileInfo.MoveTo()

查看:1104
本文介绍了文件或文件夹重命名为小写在C#中使用DirectoryInfo / FileInfo.MoveTo()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a program that renames files or folders to lower case names.

我写了以下代码:

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

我遇到了一个例外:


源和目标路径必须不同。

"Source and destination path must be different."

我如何解决这个问题?

推荐答案

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

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.

这篇关于文件或文件夹重命名为小写在C#中使用DirectoryInfo / FileInfo.MoveTo()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆