Sunday, February 14, 2010

Encoding usernames and passwords in FTP URIs

I want to encode the following into a single URI:

  • Username: ''
  • password: 'my password' (with a space)
  • ftp server: ''

The FTP URI that I expect:

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");