C#正则表达式验证文件名

San*_*yak 2 c# regex

我想用 string.Empty 替换这些字符:'"<>?*/\| 在给定的文件名中如何使用正则表达式来做到这一点我试过这个:

Regex r = new Regex("(?:[^a-z0-9.]|(?<=['\"]))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
                 FileName = r.Replace(FileName, String.Empty);
Run Code Online (Sandbox Code Playgroud)

但这会用 String.Empty 替换所有特殊字符。

Dar*_*rov 5

您可以使用Regex.Replace方法。它的作用正如它的名字所暗示的那样。

Regex regex = new Regex(@"[\\'\\""\\<\\>\\?\\*\\/\\\\\|]");
var filename = "dfgdfg'\"<>?*/\\|dfdf";
filename = regex.Replace(filename, string.Empty);
Run Code Online (Sandbox Code Playgroud)

但我宁愿对您当前使用的文件系统下的文件名中禁止的所有字符进行清理,而不仅仅是您在正则表达式中定义的字符,因为您可能忘记了一些东西:

private static readonly char[] InvalidfilenameCharacters = Path.GetInvalidFileNameChars();

public static string SanitizeFileName(string filename)
{
    return new string(
        filename
            .Where(x => !InvalidfilenameCharacters.Contains(x))
            .ToArray()
    );
}
Run Code Online (Sandbox Code Playgroud)

进而:

var filename = SanitizeFileName("dfgdfg'\"<>?*/\\|dfdf");
Run Code Online (Sandbox Code Playgroud)