我试图使用此代码将文件上传到FTP,我遇到的问题是,当语法命中serverURI.Scheme!= Uri.UriSchemeFtp时,它返回false.这是否意味着我的URI地址设置不正确?我知道这是一个有效的地址,我使用ftptest.net来验证网站是否正常运行.我的语法有什么不对?
private void button1_Click(object sender, EventArgs e)
{
Uri serverUri = new Uri("ftps://afjafaj.org");
string userName = "Ricard";
string password = "";
string filename = "C:\\Book1.xlsx";
ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;
UploadFile(serverUri, userName, password, filename);
}
public bool AcceptAllCertificatePolicy(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public bool UploadFile(Uri serverUri, string userName, string password, string fileName)
{
if (serverUri.Scheme != Uri.UriSchemeFtp)
return false;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.EnableSsl = true;
request.Credentials = new NetworkCredential(userName, password);
request.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStream = new StreamReader(fileName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Response status: {0}", response.StatusDescription);
}
catch (Exception exc)
{
throw exc;
}
return true;
}
解决方法:
ftps://前缀不是standard IANA URI scheme.只有ftp:// scheme,由RFC 1738定义.
无论如何,ftps://仍被某些软件识别为引用FTP over TLS / SSL协议(安全FTP).这模仿https://方案,它是HTTP over TLS / SSL(https://是标准方案).
虽然.NET框架无法识别ftps://.
要通过TLS / SSL连接到显式模式FTP,请将URI更改为ftp://,并将FtpWebRequest.EnableSsl
设置为true(您已经在做什么).
请注意,ftps://前缀通常是指通过TLS / SSL的隐式模式FTP. .NET框架仅支持显式模式.虽然你的URI确实是指隐式模式,但大多数服务器都支持显式模式.所以这通常不会成为问题.对于显式模式,有时会使用ftpes://.请参阅我的文章,了解FTP over TLS/SSL implicit and explicit modes之间的区别.