2012-03-08 2 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); 
    } 
} 
} 
관련 문제