[英]How to change file and directory name using c# regex
I am new at C#. 我是C#的新手。 I want to write a programme for changing files' and directories' names.
我想编写一个用于更改文件名和目录名的程序。
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
}
I want to work on path C:\\Users\\dell\\Desktop\\abc
. 我想在路径
C:\\Users\\dell\\Desktop\\abc
。 How can I add this path to my programme? 如何将此路径添加到我的程序中?
There are many special cases you should handle to encode a file name as URL, couldn't you use HttpServerUtility.UrlEncode()? 在将文件名编码为URL时,应该处理很多特殊情况,您不能使用HttpServerUtility.UrlEncode()吗? I'm not sure this is what you want anyway:
我不确定这是否是您想要的:
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.