使用的FtpWebRequest下载文件 [英] Downloading Files Using FTPWebRequest

查看:149
本文介绍了使用的FtpWebRequest下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的FtpWebRequest下载文件。

I'm trying to download a file using FTPWebRequest.

    private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
    {
        int bytesRead = 0;
        byte[] buffer = new byte[1024];

        FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        Stream reader = request.GetResponse().GetResponseStream();
        BinaryWriter writer = new BinaryWriter(File.Open(localDestinationFilePath, FileMode.CreateNew));

        while (true)
        {
            bytesRead = reader.Read(buffer, 0, buffer.Length);

            if (bytesRead == 0)
                break;

            writer.Write(buffer, 0, bytesRead);
        }        
    }

它使用我创造了这个CreateFtpWebRequest方式:

It uses this CreateFtpWebRequest method I created:

    private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive = false)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirectoryPath));

        //Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
        request.Proxy = null;

        request.UsePassive = true;
        request.UseBinary = true;
        request.KeepAlive = keepAlive;

        request.Credentials = new NetworkCredential(userName, password);

        return request;
    }

它下载它。但信息总是损坏。任何人都知道怎么回事?

It downloads it. But the information is always corrupted. Anyone know whats going on?

推荐答案

只要想通了:

    private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
    {
        int bytesRead = 0;
        byte[] buffer = new byte[2048];

        FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        Stream reader = request.GetResponse().GetResponseStream();
        FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);

        while (true)
        {
            bytesRead = reader.Read(buffer, 0, buffer.Length);

            if (bytesRead == 0)
                break;

            fileStream.Write(buffer, 0, bytesRead);
        }
        fileStream.Close();       
    }

只好用一个FileStream代替。

Had to use a FileStream instead.

这篇关于使用的FtpWebRequest下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆