我需要一些指导.我需要在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)
接受的答案确实有效。但我发现注册前缀、实现接口以及所有这些东西太麻烦了,特别是如果您只需要一次传输。
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 服务器上传和下载二进制文件
归档时间: |
|
查看次数: |
8274 次 |
最近记录: |