我需要一些指导。我需要开发一个可自定义的 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);
}
接受的答案确实有效。但我认为注册前缀,实现接口等等都太繁琐了,特别是如果你只需要它进行一次传输。
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
属性。
其他情况,请参见:
在C#/.NET中上传和下载二进制文件到FTP服务器
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
- Sphinxxx