我有一个程序可以将文件或文件夹重命名为小写。我写了这段代码:
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);
}
}
}
}
但是我得到以下异常:
“源路径和目标路径必须不同。”
我该如何解决这个问题?
最佳答案
由于Windows不区分大小写,因此就文件名而言,您需要将文件重命名为临时名称,然后使用小写字母重命名。
关于c# - 使用DirectoryInfo/FileInfo.MoveTo()在C#中将文件或文件夹重命名为小写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8152731/