System.Uri can't parse when password or username field contains a special character
The following code throws System.UriFormatException:
var uri = new UriBuilder("ftp://user:pass#word@ftp.somewhere.com: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.
- Is a # symbol a valid characte开发者_如何学编程r to have in the password field?
- Is there a way to escape this?
- Is this a known bug in the parsing routine of the Uri class?
- How does one get around this - assuming you can't change the password? ;-)
Thanks, Andrew
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 the System.Web
assembly):
string username = ...
string password = ...
string url = string.Format("ftp://{0}:{1}@ftp.example.com:21/fu/bar.zip", HttpUtility.UrlEncode(username),
HttpUtility.UrlEncode(password));
The # would need to be encoded, since it's considered a special character. Even then, not sure it would work. Never tried.
精彩评论