【发布时间】:2011-05-18 21:58:19
【问题描述】:
我需要一些指导。我需要在 C# 中开发一个可自定义的 FTP,应该使用 App.Config 文件进行配置。此外,FTP 应该再次将数据从任何客户端推送到任何服务器,这取决于配置文件。
如果有人可以指导,如果有任何 API 或任何其他有用的建议,或者让我朝着正确的方向前进,我将不胜感激。
【问题讨论】:
我需要一些指导。我需要在 C# 中开发一个可自定义的 FTP,应该使用 App.Config 文件进行配置。此外,FTP 应该再次将数据从任何客户端推送到任何服务器,这取决于配置文件。
如果有人可以指导,如果有任何 API 或任何其他有用的建议,或者让我朝着正确的方向前进,我将不胜感激。
【问题讨论】:
您可以使用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);
}
【讨论】:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
接受的答案确实有效。但是我发现注册前缀、实现接口和所有这些东西太麻烦了,特别是如果你只需要它进行一次传输。
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);
}
其他场景见:
Upload and download a binary file to/from FTP server in C#/.NET
【讨论】:
我们使用edtFTPnet 效果很好。
【讨论】: