tags:

views:

167

answers:

2

The following code throws System.UriFormatException:

var uri = new UriBuilder("ftp://user:pass#[email protected]:21/fu/bar.zip");

System.UriFormatException: Invalid URI: A port was expected because of there is a colon (':') present but the port could not be parsed.

Removing the # symbol from the password field solves the issue.

  1. Is a # symbol a valid character to have in the password field?
  2. Is there a way to escape this?
  3. Is this a known bug in the parsing routine of the Uri class?
  4. How does one get around this - assuming you can't change the password? ;-)

Thanks, Andrew

+1  A: 

The # would need to be encoded, since it's considered a special character. Even then, not sure it would work. Never tried.

Chris
With a slightly red face (I really should have thought about encoding those fields)... just to confirm, it does work when encoded.
Andrew
+1  A: 

You should be able to use %23 instead.

The percent symbol followed by a two digit hex number is how characters are escaped in URLs. 23 is the hexadecimal value for the hash/pound symbol in the ASCII table.

Rather than solving this particular problem, you should solve this problem generally by encoding the whole username and password fields. You should be able to do this with System.Web.HttpUtility.UrlEncode() (reference System.Web):

string username = ...
string password = ...
string url = string.Format("ftp://{0}:{1}@ftp.somewhere.com:21/fu/bar.zip",  HttpUtility.UrlEncode(username),
                                                              HttpUtility.UrlEncode(password));
Paul Ruane
thanks Paul, as mentioned in the comment to Chris, I really should have thought to encode the values *blush*I've changed the answer I consider correct to be yours as I believe it more accurately answers the question.
Andrew