2010-06-10 46 views
1

我試圖重命名我的程序列出的具有「非法字符」的SharePoint文件導入文件。我所指的非法字符是:〜#%& * {}/\ | :<>? - 「」使用正則表達式和遞歸更改FileNames

我想要做的是通過驅動器遞歸,收集文件名列表,然後通過正則表達式,從列表中挑選出文件名並嘗試替換實際文件名中的無效字符他們自己。

任何人有任何想法如何做到這一點?到目前爲止,我有這樣的:(請記住,我是一個完整的n00b這種東西)

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] files = Directory.GetFiles(@"C:\Documents and Settings\bob.smith\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories); 
     foreach (string file in files) 
     { 
      Console.Write(file + "\r\n"); 


     } 
     Console.WriteLine("Press any key to continue..."); 
     Console.ReadKey(true); 



     string pattern = " *[\\~#%&*{}/:<>?|\"-]+ *"; 
     string replacement = " "; 
     Regex regEx = new Regex(pattern); 

     string[] fileDrive = Directory.GetFiles(@"C:\Documents and Settings\bob.smith\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories); 
     StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\bob.smith\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt"); 
     foreach(string fileNames in fileDrive) 
     { 

     string sanitized = regEx.Replace(fileNames, replacement); 
     sw.Write(sanitized + "\r\n"); 
     } 
     sw.Close(); 



    } 






} 

所以我需要弄清楚的是如何遞歸搜索這些無效字符,在實際文件名替換它們本身。任何人有任何想法?

+0

我認爲他只是意味着把它們撕掉 – slf 2010-06-10 15:45:41

+0

正則表達式做你想做的事情嗎? – slf 2010-06-10 15:49:12

回答

1

當您遞歸處理文件和目錄時,很多時候使用DirectoryInfo類更容易,它是成員而不是靜態方法。你有一個預先建好的樹狀結構,所以你不必自己管理它。

GetDirectories返回更多DirectoryInfo實例,因此您可以走樹,而GetFiles返回FileInfo對象。

這個人created a custom iterator以遞歸方式產生文件信息,當你將它與現有的正則表達式工作相結合,將完成你的解決方案。

+0

我看了一下自定義迭代器鏈接。我在哪裏通過我想鑽入的目錄? – yeahumok 2010-06-10 17:58:47

+0

'GetFilesRecursive(dirInfo);' - 只傳遞一個根目錄dirInfo – slf 2010-06-10 21:54:24

1

File.Move()有效地重命名文件。基本上,你只需要

File.Move(fileNames, sanitized); 

在後面的循環。

ALERT - 可能就會有重複的文件名,所以你必須建立一個政策來避免這種情況,像在sanitized變量的末尾附加一個計數器。另外,應用適當的異常處理。 PS:當然,你不需要搜索字符如:\*

+0

我需要在這裏放置一個if/else語句嗎?或者如果文件沒有無效字符,它會自動跳過它? – yeahumok 2010-06-10 20:17:11

+0

@yeahumok,你確實可以將'fileNames'與'sanitized'進行比較,以避免不必要地調用'File.Move()'。但是,請注意重複(例如,'#File.txt'和'〜File.txt'將被命名爲'File.txt'),並檢查訪問權限,磁盤空間和其他IO異常。 – Humberto 2010-06-10 21:39:28