我有这样的代码:问题与现有的文件名和创建一个唯一的文件名
public void FileCleanup(List<string> paths)
{
string regPattern = (@"[~#&!%+{}]+");
string replacement = "";
string replacement_unique = "_";
Regex regExPattern = new Regex(regPattern);
List<string> existingNames = new List<string>();
StreamWriter errors = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\SharePointTesting\Errors.txt");
StreamWriter resultsofRename = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\SharePointTesting\Results of File Rename.txt");
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))
{
existingNames.Add(sanitized);
try
{
foreach (string names in existingNames)
{
string filename = Path.GetFileName(names);
string filepath = Path.GetDirectoryName(names);
string cleanName = regExPattern.Replace(filename, replacement_unique);
string scrubbed = Path.Combine(filepath, cleanName);
System.IO.File.Move(names, scrubbed);
//resultsofRename.Write("Path: " + pathOnly + "/" + "Old File Name: " + filenameOnly + "New File Name: " + sanitized + "\r\n" + "\r\n");
resultsofRename = File.AppendText("Path: " + filepath + "/" + "Old File Name: " + filename + "New File Name: " + scrubbed + "\r\n" + "\r\n");
}
}
catch (Exception e)
{
errors.Write(e);
}
}
else
{
System.IO.File.Move(files2, sanitized);
resultsofRename.Write("Path: " + pathOnly + "/" + "Old File Name: " + filenameOnly + "New File Name: " + sanitized + "\r\n" + "\r\n");
}
}
catch (Exception e)
{
//write to streamwriter
}
}
}
}
什么,我想在这里做的是通过除去无效字符(在正则表达式定义)重命名“脏”的文件名,用“”替换它们。不过,我注意到如果我有重复的文件名,应用程序不会重命名它们。即如果我在同一个文件夹中有## test.txt和~~ test.txt,它们将被重命名为test.txt。所以,我创建了另一个foreach循环,用一个“_”替代了无效字符而不是空格。
问题是,每当我试图运行这个,没有结果发生!没有文件被重命名!
有人可以告诉我,如果我的代码是不正确的,如何解决它?
也有人知道我怎么能替换第二个foreach循环中的无效字符与每次不同的字符?这样,如果有多个实例,即%Test.txt,〜Test.txt和#test.txt(全部要重命名为test.txt),它们可以以不同的方式用不同的char来唯一命名?
这可能是因为那些肮脏的名字损害你的执行。最重要的是给我们例外信息。 – eugeneK 2010-06-30 13:20:51
您是否调试过代码以缩小问题的严重程度? – 2010-06-30 13:21:22
我做了一个编辑 - 我想出了为什么我的代码没有步进到第二个foreach循环。但是,您是否知道如何每次使用不同的唯一字符替换无效字符,以便每个文件名都保持唯一? – yeahumok 2010-06-30 13:26:46