Sunday, February 14, 2010

Encoding usernames and passwords in FTP URIs

I want to encode the following into a single URI:

  • Username: 'jane+foo@example.com'
  • password: 'my password' (with a space)
  • ftp server: 'ftp.example.org'

The FTP URI that I expect:

ftp://jane%2bfoo%40example.com:my%20password@ftp.example.org

In .NET, HttpUtility.UrlEncode almost does what I need - it hex-encodes the special chars, but it also converts spaces to "+" which the FTP server interprets as a literal "+".

Final code that works with my tests using the FileZilla FTP Server:

string EncodeFtpUserInfoComponent(string s)
{
  // assume or assert s != null
  return HttpUtility.UrlEncode(s).Replace("+", "%20");
}

No comments:

Post a Comment