.NET的安全/允许文件名清除程序

Cra*_*ker 6 .net windows filenames

在.NET中是否有任何标准化/图书馆/测试方式来获取任意字符串并以一种表示有效文件名的方式对其进行修改?

滚动我自己的char-replace功能很容易,但我想要一些更强大和更新的东西.

Kon*_*man 14

您可以使用Path.GetInvalidFileNameChars来检查字符串的哪些字符无效,并将它们转换为有效的字符串(如连字符),或者(如果需要双向转换)用转义标记替换它们,例如%,跟随十六进制他们的unicode代码的表示(我实际上曾使用过这种技术,但现在没有手头的代码).

编辑:以防有人感兴趣,这是代码.

/// <summary>
/// Escapes an object name so that it is a valid filename.
/// </summary>
/// <param name="fileName">Original object name.</param>
/// <returns>Escaped name.</returns>
/// <remarks>
/// All characters that are not valid for a filename, plus "%" and ".", are converted into "%uuuu", where uuuu is the hexadecimal
/// unicode representation of the character.
/// </remarks>
private string EscapeFilename(string fileName)
{
    char[] invalidChars=Path.GetInvalidFileNameChars();

    // Replace "%", then replace all other characters, then replace "."

    fileName=fileName.Replace("%", "%0025");
    foreach(char invalidChar in invalidChars)
    {
        fileName=fileName.Replace(invalidChar.ToString(), string.Format("%{0,4:X}", Convert.ToInt16(invalidChar)).Replace(' ', '0'));
    }
    return fileName.Replace(".", "%002E");
}

/// <summary>
/// Unescapes an escaped file name so that the original object name is obtained.
/// </summary>
/// <param name="escapedName">Escaped object name (see the EscapeFilename method).</param>
/// <returns>Unescaped (original) object name.</returns>
public string UnescapeFilename(string escapedName)
{
    //We need to temporarily replace %0025 with %! to prevent a name
    //originally containing escaped sequences to be unescaped incorrectly
    //(for example: ".%002E" once escaped is "%002E%0025002E".
    //If we don't do this temporary replace, it would be unescaped to "..")

    string unescapedName=escapedName.Replace("%0025", "%!");
    Regex regex=new Regex("%(?<esc>[0-9A-Fa-f]{4})");
    Match m=regex.Match(escapedName);
    while(m.Success)
    {
        foreach(Capture cap in m.Groups["esc"].Captures)
            unescapedName=unescapedName.Replace("%"+cap.Value, Convert.ToChar(int.Parse(cap.Value, NumberStyles.HexNumber)).ToString());
        m=m.NextMatch();
    }
    return unescapedName.Replace("%!", "%");
}
Run Code Online (Sandbox Code Playgroud)


Dou*_*rch 9

这个问题并不像你想象的那么简单.这些字符不仅是Path.GetInvalidFileNameChars非法的,还有几个文件名,例如"PRN"和"CON",它们是由Windows保留的,无法创建.任何以"."结尾的名称.在Windows中也是非法的.而且,存在各种长度限制.阅读完整的列表在这里.

如果这还不够,不同的文件系统有不同的限制,例如ISO 9660文件名不能以" - "开头,但可以包含它.