我有這樣的代碼:問題與現有的文件名和創建一個唯一的文件名
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