在c#中使用ftp下载文件

时间:2015-05-15 13:41:08

标签: c# ftp

我需要更改旧系统中的逻辑,我试图让下载文件工作,任何想法?我需要在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();  

1 个答案:

答案 0 :(得分:0)

评论者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();