【问题标题】:Downloading file via FTP fails (only downloads portion of file)通过 FTP 下载文件失败(仅下载文件的一部分)
【发布时间】:2015-08-07 13:57:22
【问题描述】:

以下是从 FTP 下载内容的方法,但如果我只是让程序运行,它会失败。 如果我慢慢地浏览代码,它就可以工作。 如果我让它自己运行,它只会下载 5kb 的文件,然后继续运行。 它不会抛出异常,它只是下载 5kb 然后退出,继续下一个项目。

private static void DownloadFtpFile(string sourceFileLocation)
    {
        try
        {
                int bufferSize = 1024 * 300;
                int totalBytes = 0;
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceFileLocation);
                long contentLength = webRequest.GetResponse().ContentLength;
                Console.WriteLine(totalBytes);

                using (WebResponse webResponse = webRequest.GetResponse())
                using (Stream reader = webResponse.GetResponseStream())
                using (BinaryWriter fileWriter = new BinaryWriter(File.Create(Application.StartupPath + "\\" + "tempFldr" + "\\" + "tempFile")))
                {
                    int bytesRead = 0;
                    byte[] buffer = new byte[bufferSize];
                    do
                    {
                        bytesRead = reader.Read(buffer, 0, buffer.Length);
                        totalBytes += bytesRead;
                        fileWriter.Write(buffer, 0, bytesRead);
                        Console.WriteLine("BytesRead: " + bytesRead + " -- TotalBytes: " + totalBytes);

                    } while (bytesRead > 0);
                }
            }
        catch (WebException ex)
        {
            String status = ((HttpWebResponse)ex.Response).StatusDescription;
            Console.WriteLine(status);
        }
    }

【问题讨论】:

    标签: c# download ftp httpwebrequest


    【解决方案1】:

    首先,尝试从 HttpWebRequest 切换到 FtpWebRequest。不确定这是否会产生巨大的影响,但如果您从 FTP 获取内容,它可能会。

    我觉得你可能会从使用 do-while 改为使用类似这样的 while:

    byte[] buffer = new byte[bufferSize];
    int bytesRead;
    while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileWrite.Write(chunk, 0, bytesRead);
        totalBytes += bytesRead;
        Console.WriteLine("BytesRead: " + bytesRead + " -- TotalBytes: " + totalBytes);
    }
    

    您可能会考虑其他一些事情,也许只是将文件下载到流中,然后在您关闭 FTP 连接后将其保存到文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多