无效的 URI:指定的端口无效/无法解析主机名

Invalid URI: Invalid port specified / The hostname could not be parsed

我正在尝试将文件上传到远程服务器的 FTP。

当我尝试使用时: ftp://user:pass@ftp.host.com/name.txt

我收到此错误: 无效的 URI: 指定的端口无效。

当我尝试使用时: ftp://[user:pass@ftp.host.com]/name.txt

正如几篇帖子中所建议的那样,

我收到此错误: 无效的 URI:无法解析主机名。

这是我的上传代码:

using (System.Net.WebClient webClient = new System.Net.WebClient())
{
    webClient.UploadFile(new Uri(ftpAddress), @"C:\inetpub\wwwroot\name.txt");
}

我猜你的密码或用户名包含使 uri 无效的符号。因此,您应该使用另一种方式来设置凭据:

var uri = new Uri("ftp://ftp.host.com/name.txt"); //no credentails in url
using (var webClient = new System.Net.WebClient())
{
    webClient.Credentials = new System.Net.NetworkCredential("user", "pass");
    webClient.DownloadFile(uri, @"C:\inetpub\wwwroot\name.txt");
}

或者您仍然可以使用 URL 中的密码,但您需要按以下方式对特殊字符进行编码:

# -> %23     
/ -> %2F     
: -> %3A     
? -> %3F     
\ -> %5C     
% -> %25