-2

The code here is giving me the error "{"Invalid URI: The hostname could not be parsed."}"

var downloadUri = ConfigurationManager.AppSettings["DownloadUri"];

FtpWebRequest FTPRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" 
+ "user123" +
":" + "p@ssword" + "@" + downloadUri);

The ftp password here has an @ character which when removed allows this piece of code to continue. But the password has an @ character so how can I make this work?

user3654442
  • 179
  • 1
  • 4
  • 19

1 Answers1

4

You need to hex-encode the @ symbol:

string encodedPassword = "p@ssword".Replace("@", "%40");

FtpWebRequest FTPRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" 
    + "user123" +
    ":" + encodedPassword + "@" + downloadUri);

(At the suggestion of Andrew) If you want to catch more "specialized" characters:

Add a reference to System.Web and use the following:

string encodedPassword = HttpUtility.UrlEncode("p@ssword");

FtpWebRequest FTPRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" 
    + "user123" +
    ":" + encodedPassword + "@" + downloadUri);

Or, even better:

string userName = "user123";
string password = "p@ssword";
string ftpPath = string.Format("ftp://{0}:{1}@{2}", userName, password, downloadUri);

var ftpRequest = (FtpWebRequest)FtpWebRequest.Create(HttpUtility.UrlEncode(ftpPath));
Ron Beyer
  • 11,003
  • 1
  • 19
  • 37
  • 1
    I would use `HttpUtility.UrlEncode` instead of hardcoding that logic. What if the password also has `:`, `/`, or any other problematic character? – Andrew Mar 21 '18 at 20:03
  • @Andrew Probably better to do it that way, although would require the OP to reference `System.Web`. It is unclear though whether `UrlEncode` or `UrlPathEncode` would be better in this situation since they encode slightly differently (spaces for example are `+` in UrlEncode, and `%20` in UrlPathEncode). – Ron Beyer Mar 21 '18 at 20:06
  • @Andrew `WebUtility.UrlEncode()` is in `System.Net` and outputs the same thing. – Jimi Mar 21 '18 at 20:45
  • Right, apparently it's pretty much the same, but the encodings are always uppercase: https://stackoverflow.com/a/21771206/2321042. – Andrew Mar 21 '18 at 23:34