使用 FtpWebRequest 下载文件 [英] Downloading files Using FtpWebRequest

查看:37
本文介绍了使用 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 what's 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天全站免登陆