gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:15:57 27 4
gpt4 key购买 nike

在 .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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com