在c#中使用ftp下载文件
本文关键字:ftp 下载 文件 | 更新日期: 2023-09-27 17:49:27
我需要改变旧系统中的逻辑,我试图让下载文件工作,有什么想法吗?我需要在c#中使用FTP下载文件这是我找到的代码但我需要将其放入文件而不是流
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.1.52/Odt/"+fileName+".dat");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
来自评论员Ron Beyer的建议不错,但是因为它涉及到解码和重新编码文本,所以存在数据丢失的风险。
您可以通过直接将请求响应流复制到文件中来逐字下载文件。它看起来像这样:
// Some file name, initialized however you like
string fileName = ...;
using (Stream responseStream = response.GetResponseStream())
using (Stream fileStream = File.OpenWrite(filename))
{
responseStream.CopyTo(fileStream);
}
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
response.Close();