2012-03-08 10 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で作業したいです。 このパスをプログラムに追加するにはどうすればよいですか?あなたはURLとしてファイル名をエンコードするために処理する必要があり多く特殊なケースがあり

答えて

1

、あなたが使用することができませんでし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); 
    } 
} 
} 
関連する問題