开发者

System.Uri can't parse when password or username field contains a special character

开发者 https://www.devze.com 2022-12-22 01:39 出处:网络
The following code throws System.UriFormatException: var uri = new UriBuilder(\"ftp://user:pass#word@ftp.somewhere.com:21/fu/bar.zip\");

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.

  1. Is a # symbol a valid characte开发者_如何学编程r 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消