C# Uri.AbsolutePath 用空格弄乱了路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/436520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:20:30  来源:igfitidea点击:

Uri.AbsolutePath messes up path with spaces

c#.net-2.0system.netwinapp

提问by JohnIdol

In a WinApp I am simply trying to get the absolute path from a Uri object:

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

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

This works fine if no spaces in my original path. If spaces are in there the string gets mangled; for example 'Documents and settings' becomes 'Documents%20and%20Setting' etc.

如果我的原始路径中没有空格,这可以正常工作。如果那里有空格,则字符串会被破坏;例如“文档和设置”变为“文档%20and%20Setting”等。

Any help would be appreciated!

任何帮助,将不胜感激!

EDIT:LocalPath instead of AbsolutePath did the trick!

编辑:LocalPath 而不是 AbsolutePath 成功了!

采纳答案by Steven Robbins

It's encoding it as it should, you could probably UrlDecode it to get it back with spaces, but it's not "mangled" it's just correctly encoded.

它按照它应该的方式对其进行编码,您可能可以通过 UrlDecode 将其带回空格,但它没有“损坏”,它只是正确编码。

I'm not sure what you're writing, but to convert it back in asp.net it's Server.UrlDecode(path). You also might be able to use LocalPath, rather than AbsolutePath, if it's a Windows app.

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

回答by EndangeredMassa

This is the way it's supposed to be. That's called URL encoding. It applies because spaces are not allowed in URLs.

这是它应该的方式。这称为 URL 编码。它适用是因为 URL 中不允许有空格。

If you want the path back with spaces included, you must call something like:

如果您希望包含空格的路径返回,则必须调用以下内容:

string path = Server.URLDecode(myUri.AbsolutePath);

You shouldn't be required to import anything to use this in a web application. If you get an error, try importing System.Web.HttpServerUtility. Or, you can call it like so:

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

string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath);

回答by Gishu

Uri also has a couple of static methods - EscapeDataStringand EscapeUriString.

Uri 还有几个静态方法 - EscapeDataString和 EscapeUriString。

Uri.EscapeDataString(uri.AbsolutePath)also works

Uri.EscapeDataString(uri.AbsolutePath)也有效

回答by Andreas

Just use uri.LocalPath instead

只需使用 uri.LocalPath 代替

回答by Rana

Use HttpUtility:

使用 HttpUtility:

 HttpUtility.UrlDecode(uri.AbsolutePath)