C#中的FTPS(基于SSL的FTP)

use*_*963 10 .net c# winforms

我需要一些指导.我需要在C#中开发一个可自定义的FTP,它应该使用App.Config文件进行配置.此外,FTP应该再次从任何客户端将数据推送到任何服务器依赖于配置文件.

如果有人可以指导,如果有任何API或任何其他有用的建议,或者让我朝着正确的方向前进,我将不胜感激.

Edw*_*rey 17

你可以使用FtpWebRequest ; 然而,这是相当低的水平.有一个更高级别的WebClient类,它在许多场景中需要的代码要少得多; 但是,默认情况下它不支持FTP/SSL.幸运的是,您可以WebClient通过注册自己的前缀来使用FTP/SSL:

private void RegisterFtps()
{
    WebRequest.RegisterPrefix("ftps", new FtpsWebRequestCreator());
}

private sealed class FtpsWebRequestCreator : IWebRequestCreate
{
    public WebRequest Create(Uri uri)
    {
        FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(uri.AbsoluteUri.Remove(3, 1)); // Removes the "s" in "ftps://".
        webRequest.EnableSsl = true;
        return webRequest;
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦你这样做,你可以使用WebClient几乎像普通的一样,除了你的URI以"ftps://"而不是"ftp://"开头.需要注意的是,您必须指定method参数,因为不存在默认参数.例如

using (var webClient = new WebClient()) {
    // Note here that the second parameter can't be null.
    webClient.UploadFileAsync(uploadUri, WebRequestMethods.Ftp.UploadFile, fileName, state);
}
Run Code Online (Sandbox Code Playgroud)

  • @Sphinxxx 请注意,盲目接受任何服务器证书会让您容易受到中间人攻击。 (2认同)
  • 通常,您只需确保服务器具有与其主机名匹配的 SSL 证书,就像处理任何 HTTPS 流量一样。如果您无法做到这一点,您可以[验证自签名证书](/sf/answers/36876241/)。 (2认同)

Mar*_*ryl 7

接受的答案确实有效。但我发现注册前缀、实现接口以及所有这些东西太麻烦了,特别是如果您只需要一次传输。

FtpWebRequest使用起来并不困难。所以我认为对于一次性使用,最好采用这种方式:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.EnableSsl = true;
request.Method = WebRequestMethods.Ftp.UploadFile;  

using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
    fileStream.CopyTo(ftpStream);
}
Run Code Online (Sandbox Code Playgroud)

关键是EnableSsl属性


对于其他场景,请参阅:
在 C#/.NET 中向 FTP 服务器上传和下载二进制文件


Adr*_*der 2

我们使用edtFTPnet,效果很好。

  • 只是为了让人们知道免费版本不支持 FTPS,专业版本支持 (7认同)