JohnIdol
JohnIdol

Reputation: 50117

Uri.AbsolutePath messes up path with spaces

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

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.

Any help would be appreciated!

EDIT: LocalPath instead of AbsolutePath did the trick!

Upvotes: 17

Views: 16153

Answers (5)

Rana
Rana

Reputation: 1218

Use HttpUtility:

 HttpUtility.UrlDecode(uri.AbsolutePath)

Upvotes: 0

Andreas
Andreas

Reputation: 4013

Just use uri.LocalPath instead

Upvotes: 7

Gishu
Gishu

Reputation: 136633

Uri also has a couple of static methods - EscapeDataString and EscapeUriString.

Uri.EscapeDataString(uri.AbsolutePath) also works

Upvotes: 3

EndangeredMassa
EndangeredMassa

Reputation: 17528

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

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:

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

Upvotes: 13

Steven Robbins
Steven Robbins

Reputation: 26599

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.

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.

Upvotes: 11

Related Questions