.net - .NET 的安全/允许的文件名清理器

标签 .net windows filenames

在 .NET 中是否有任何标准化/库化/测试的方法来获取任意字符串并以表示有效文件名的方式对其进行处理?

滚动我自己的 char-replace 函数很容易,但我想要一些更健壮和resued的东西。

最佳答案

您可以使用 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("%!", "%");
}

关于.net - .NET 的安全/允许的文件名清理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1862993/

相关文章:

windows - 如何指定在哪个监视器上打开控制台窗口?

c# - 有没有办法告诉我在运行时使用的是哪个枚举?

c# - 在没有窗口聚焦的情况下获取键盘事件

c# - 无法从 Windows 7 上的 Windows 服务启动桌面应用程序

css - 在 Microsoft 环境中离线安装 SaSS

powershell - 使用 powershell 将双引号写入文件名文本

c# - 如何从 C# 中的文件路径中删除引号和命令行参数?

JavaScript 改变默认文件名?

c# - 无论 C# 中的基础类型如何,System.Enum 值的一般处理

c# - MSBuild 无法构建 MSI。 Windows 服务有替代方案吗?