【问题标题】:FTPS (FTP over SSL) in C#C# 中的 FTPS(基于 SSL 的 FTP)
【发布时间】:2011-05-18 21:58:19
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    您可以使用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;
        }
    }
    

    完成此操作后,您几乎可以像平常一样使用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);
    }
    

    【讨论】:

    • 来自a duplicate answer 的cmets:要自动接受客户端可能遇到的任何证书,这可行:ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
    • @Sphinxxx 请注意,盲目接受任何服务器证书会使您容易受到中间人攻击。
    • 是的,这不是最优雅的解决方案。你有更安全的选择吗?
    • 通常,您只需确保服务器具有与其主机名匹配的 SSL 证书,就像处理任何 HTTPS 流量一样。如果你做不到,你可以validate a self-signed certificate
    【解决方案2】:

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

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

    密钥是EnableSsl property


    其他场景见:
    Upload and download a binary file to/from FTP server in C#/.NET

    【讨论】:

      【解决方案3】:

      我们使用edtFTPnet 效果很好。

      【讨论】:

      • 只是为了让人们知道免费版不支持 FTPS,专业版支持
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      相关资源
      最近更新 更多