gpt4 book ai didi

c# - File.Move() 重命名不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:26 24 4
gpt4 key购买 nike

我的应用采用“不干净”的文件名并“清理”它们。 “不干净”文件名包含@、#、~、+、% 等字符。“清理”过程用“”替换这些字符。但是,我发现如果同一文件夹中有两个文件在清理后具有相同的名称,我的应用程序不会重命名任何一个文件。 (即 ##test.txt 和 ~test.txt 都将在清理后命名为 test.txt)。

因此,我放入了一个循环,基本上检查我的应用程序尝试重命名的文件名是否已存在于文件夹中。但是,我尝试运行它,但它不会重命名所有文件。我做错了什么吗?

这是我的代码:

        public void FileCleanup(List<string> paths)
{
string regPattern = (@"[~#&!%+{}]+");
string replacement = "";

Regex regExPattern = new Regex(regPattern);
List<string> existingNames = new List<string>();
StreamWriter errors = new StreamWriter(@"C:\Documents and Settings\joe.schmoe\Desktop\SharePointTesting\Errors.txt");
StreamWriter resultsofRename = new StreamWriter(@"C:\Documents and Settings\joe.schmoe\Desktop\SharePointTesting\Results of File Rename.txt");

var filesCount = new Dictionary<string, int>();
string replaceSpecialCharsWith = "_";

foreach (string files2 in paths)

try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
if (!System.IO.File.Exists(sanitized))
{
System.IO.File.Move(files2, sanitized);
resultsofRename.Write("Path: " + pathOnly + " / " + "Old File Name: " + filenameOnly + "New File Name: " + sanitized + "\r\n" + "\r\n");
}

else
{
existingNames.Add(sanitized);
foreach (string names in existingNames)
{

string sanitizedPath = regExPattern.Replace(names, replaceSpecialCharsWith);
if (filesCount.ContainsKey(sanitizedPath))
{
filesCount[names]++;
}
else
{
filesCount.Add(sanitizedPath, 1);
}

string newFileName = String.Format("{0},{1}, {2}", Path.GetFileNameWithoutExtension(sanitizedPath),
filesCount[sanitizedPath] != 0
? filesCount[sanitizedPath].ToString()
: "",
Path.GetExtension(sanitizedPath));

string newFilePath = Path.Combine(Path.GetDirectoryName(sanitizedPath), newFileName);
System.IO.File.Move(names, newFileName);

}
}
}
catch (Exception e)
{
//write to streamwriter

}

}

}

有人知道为什么我的代码不能唯一地重命名重复文件吗?

最佳答案

  • 您执行 foreach(existingNames 中的字符串名称),但是 existingNames 是空的。
  • 你的 if (System.IO.File.Exists(sanitized)) 倒过来了:如果文件不存在,而不是当文件存在时,它会创建一个新名称。<
  • 您创建了一个字符串 newFileName,但仍然使用 sanitizedPath 而不是 newFileName 来进行重命名。
  • filesCount.Add(sanitizedPath, 0) 的第二个参数应该是 1 或 2。毕竟,您随后遇到了第二个同名文件。
  • 如果 filesCount[sanitizedPath] 等于 0,则根本不更改文件名,因此会覆盖现有文件。

关于c# - File.Move() 重命名不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3152969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com