繁体   English   中英

如何使用C#正则表达式更改文件和目录名称

[英]How to change file and directory name using c# regex

我是C#的新手。 我想编写一个用于更改文件名和目录名的程序。

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时,应该处理很多特殊情况,您不能使用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);
  }
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM