2012-03-08 43 views
2

我是C#的新手。我想寫一個程序來更改文件和目錄的名稱。如何使用c#regex更改文件和目錄名稱

public static string ToUrlSlug(this string text) 
{ 
    return Regex.Replace(
     Regex.Replace(
      Regex.Replace(
       text.Trim().ToLower() 
          .Replace("ö", "o") 
          .Replace("ç", "c") 
          .Replace("ş", "s") 
          .Replace("ı", "i") 
          .Replace("ğ", "g") 
          .Replace("ü", "u"), 
           @"\s+", " "), //multiple spaces to one space 
          @"\s", "-"), //spaces to hypens 
         @"[^a-z0-9\s-]", ""); //removing invalid chars 
} 

我想在路徑C:\Users\dell\Desktop\abc上工作。 如何將此路徑添加到我的程序中?

回答

1

還有很多你應該處理的特殊情況下,將文件名編碼爲URL,難道你不能使用HttpServerUtility.UrlEncode()? 我不確定這是你想要的嗎:

public void RenameFiles(string folderPath, string searchPattern = "*.*") 
{ 
foreach (string path in Directory.EnumerateFiles(folderPath, searchPattern)) 
{ 
    string currentFileName = Path.GetFileNameWithoutExtension(path); 
    string newFileName = ToUrlSlug(currentFileName); 

    if (!currentFileName.Equals(newFileName)) 
    { 
    string newPath = Path.Combine(Path.GetDirectoryName(path), 
    newFileName + Path.GetExtension(path)); 

    File.Move(path, newPath); 
    } 
} 
} 
相關問題