Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

uri

parsing

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

like image 684
Andrew Avatar asked Mar 08 '10 13:03

Andrew


People also ask

What is a URI in C#?

A URI is a compact representation of a resource available to your application on the intranet or internet. The Uri class defines the properties and methods for handling URIs, including parsing, comparing, and combining. The Uri class properties are read-only; to create a modifiable object, use the UriBuilder class.

What is string URI?

A URI is a string containing characters that identify a physical or logical resource. URI follows syntax rules to ensure uniformity. Moreover, it also maintains extensibility via a hierarchical naming scheme. The full form of URI is Uniform Resource Identifier.


2 Answers

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));
like image 105
Paul Ruane Avatar answered Oct 21 '22 01:10

Paul Ruane


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

like image 36
Chris Avatar answered Oct 20 '22 23:10

Chris