C# UrlPathEncode()可选

C# UrlPathEncode()可选,c#,http,encoding,escaping,C#,Http,Encoding,Escaping,声明不应该使用UrlPathEncode,而应该使用UrlEncode 不要使用;仅用于浏览器兼容性。使用UrlEncode 但与UrlPathEncode做的事情不同 我的用例是,我想对文件系统路径进行编码,以便可以下载文件。路径中的空格需要转义,而不是前斜杠等。UrlPathEncode正是这样做的 // given the path string path = "Directory/Path to escape.exe"; Console.WriteLine(System.Web.Htt

声明不应该使用UrlPathEncode,而应该使用UrlEncode

不要使用;仅用于浏览器兼容性。使用UrlEncode

但与UrlPathEncode做的事情不同

我的用例是,我想对文件系统路径进行编码,以便可以下载文件。路径中的空格需要转义,而不是前斜杠等。UrlPathEncode正是这样做的

// given the path
string path = "Directory/Path to escape.exe";

Console.WriteLine(System.Web.HttpUtility.UrlPathEncode(path));
// returns "Installer/My%20Installer.msi" <- This is what I require

Console.WriteLine(System.Web.HttpUtility.UrlEncode(path));
// returns "Installer%2fMy+Installer.msi"

// none of these return what I require, either
Console.WriteLine(System.Web.HttpUtility.UrlEncode(path, Encoding.ASCII));
Console.WriteLine(System.Web.HttpUtility.UrlEncode(path, Encoding.BigEndianUnicode));
Console.WriteLine(System.Web.HttpUtility.UrlEncode(path, Encoding.Default));
Console.WriteLine(System.Web.HttpUtility.UrlEncode(path, Encoding.UTF32));
Console.WriteLine(System.Web.HttpUtility.UrlEncode(path, Encoding.UTF7));
Console.WriteLine(System.Web.HttpUtility.UrlEncode(path, Encoding.UTF8));
Console.WriteLine(System.Web.HttpUtility.UrlEncode(path, Encoding.Unicode));
问题:
如果我不应该使用UrlPathEncode,而UrlEncode没有生成所需的输出,那么什么方法是等效的和推荐的?

有趣的是,当尝试正确地编写问题时,您会发现您的答案:

Uri.EscapeUriString(路径);
生成所需的输出

不过,我确实认为MSDN页面应该反映这一点

编辑(2020-11-22)

我最近再次遇到这种情况,但需要使用特殊字符(而不是带有空格的文件名)对URL进行URL编码,但本质上是一样的。我这次使用的方法是实例化Uri类:

var urlWithSpecialChars=”https://www.example.net/something/contins spécial chars?query has=spécial chars以及”;
var uri=新uri(urlWithSpecialChars);
//产出”https://www.example.net/something/contins spécial chars?query has=spécial chars以及”
Debug.WriteLine(uri.OriginalString);
//产出”https://www.example.net/something/cont%C3%A0ins-sp%C3%A9cal字符?查询具有=sp%C3%A9cal字符”
Debug.WriteLine(uri.AbsoluteUri);
//输出“/something/cont%C3%A0ins sp%C3%A9cial chars?查询还具有=sp%C3%A9cial chars”
Debug.WriteLine(uri.PathAndQuery);
这为您提供了许多有用的Uri属性,这些属性可能涵盖大多数/许多Uri处理需求:

// returns Directory%2FPath%20to%20escape.exe
Console.WriteLine(Uri.EscapeDataString(path));