【问题标题】:Downloading files using FtpWebRequest使用 FtpWebRequest 下载文件
【发布时间】:2012-09-13 05:06:27
【问题描述】:

我正在尝试使用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 方法:

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;
}

它会下载它。但信息总是被破坏。有谁知道怎么回事?

【问题讨论】:

    标签: c# .net c#-4.0 ftp ftpwebrequest


    【解决方案1】:

    刚刚想通了:

        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。

    【讨论】:

    • 虽然此代码有效,但它过于复杂。您可以通过对Stream.CopyTo 的简单调用来替换循环。或者你甚至可以用WebClient.DownloadFile 替换整个代码。请参阅下面的答案。
    【解决方案2】:

    最简单的方法

    使用 .NET 框架从 FTP 服务器下载文件的最简单方法是使用 WebClient.DownloadFile method:

    WebClient client = new WebClient();
    client.Credentials = new NetworkCredential("username", "password");
    client.DownloadFile(
        "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
    

    高级选项

    使用FtpWebRequest class,如果您只需要更大的控制,WebClient 类不提供(如TLS/SSL encryption、进度监控、ascii/文本传输模式、resuming transfers 等)。一种简单的方法是使用Stream.CopyTo 方法将FTP 响应流复制到FileStream:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    
    using (Stream ftpStream = request.GetResponse().GetResponseStream())
    using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
    {
        ftpStream.CopyTo(fileStream);
    }
    

    进度监控

    如果你需要监控一个下载进度,你必须自己分块复制内容:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    
    using (Stream ftpStream = request.GetResponse().GetResponseStream())
    using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
    {
        byte[] buffer = new byte[10240];
        int read;
        while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fileStream.Write(buffer, 0, read);
            Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
        }
    }
    

    有关 GUI 进度 (WinForms ProgressBar),请参阅:
    FtpWebRequest FTP download with ProgressBar


    下载文件夹

    如果您想从远程文件夹下载所有文件,请参阅
    C# Download all files and subdirectories through FTP。

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      相关资源
      最近更新 更多