Vic*_*u B 0 c# encoding path decoding illegal-characters
我正在寻找一种简单的方法来编码/转义和解码/ unescape文件路径(文件路径中的非法字符"\/?:<>*| )
HttpUtiliy.UrlEncode做它的工作,除了它不编码*字符.
我所能找到的只是用正则表达式逃脱,或者只是替换非法的字符 _
我希望能够一致地编码/解码.
我想知道是否有预先定义的方法来做到这一点,或者我只需要编写一些代码进行编码,另一部分需要解码.
谢谢
我之前从未尝试过这样的事情,所以我把它扔到了一起:
static class PathEscaper
{
static readonly string invalidChars = @"""\/?:<>*|";
static readonly string escapeChar = "%";
static readonly Regex escaper = new Regex(
"[" + Regex.Escape(escapeChar + invalidChars) + "]",
RegexOptions.Compiled);
static readonly Regex unescaper = new Regex(
Regex.Escape(escapeChar) + "([0-9A-Z]{4})",
RegexOptions.Compiled);
public static string Escape(string path)
{
return escaper.Replace(path,
m => escapeChar + ((short)(m.Value[0])).ToString("X4"));
}
public static string Unescape(string path)
{
return unescaper.Replace(path,
m => ((char)Convert.ToInt16(m.Groups[1].Value, 16)).ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
它将任何禁用的字符替换为a %后跟16位十六进制表示,然后返回.(对于你所拥有的特定角色,你可能会得到一个8位的表示,但我认为我在安全方面犯了错误.)