Uri.AbsolutePath用空格弄乱了路径

Joh*_*dol 13 c# system.net winapp .net-2.0

在WinApp中,我只是想从Uri对象获取绝对路径:

Uri myUri = new Uri(myPath); //myPath is a string
//somewhere else in the code
string path = myUri.AbsolutePath;
Run Code Online (Sandbox Code Playgroud)

如果原始路径中没有空格,这可以正常工作.如果空格在那里,那么字符串会被破坏; 例如,"文档和设置"变为"文档%20和%20设置"等.

任何帮助,将不胜感激!

编辑: LocalPath而不是AbsolutePath做了伎俩!

End*_*ssa 12

这是应该的方式.这就是所谓的URL编码.它适用,因为URL中不允许使用空格.

如果您想要包含空格的路径,则必须调用以下内容:

string path = Server.URLDecode(myUri.AbsolutePath);
Run Code Online (Sandbox Code Playgroud)

您不应该要求导入任何内容以在Web应用程序中使用它.如果出现错误,请尝试导入System.Web.HttpServerUtility.或者,您可以这样称呼它:

string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath);
Run Code Online (Sandbox Code Playgroud)


Ste*_*ins 10

它正在对它进行编码,你可能会对它进行UrlDecode以使其返回空格,但它并没有被"修复"它只是正确编码.

我不确定你在写什么,但是要在asp.net中将它转换回Server.UrlDecode(path).如果它是Windows应用程序,您也可以使用LocalPath而不是AbsolutePath.

  • 如果它是Windows应用程序,您也可以使用LocalPath而不是AbsolutePath. (2认同)

And*_*eas 5

只需使用uri.LocalPath