简体   繁体   English

通过FTP下载文件失败(仅下载文件的一部分)

[英]Downloading file via FTP fails (only downloads portion of file)

Below is a method to download content from an FTP, but if I just let the program run, it fails. 下面是从FTP下载内容的方法,但是如果我让程序运行,它将失败。 If I step slowly through the code, it works. 如果我逐步浏览代码,它会起作用。 If I just let it run on its own, it only downloads 5kb of the file, and then moves on. 如果我让它自己运行,它只会下载5kb的文件,然后继续前进。 It doesn't throw an exception, it just downloads the 5kb and then quits, moving onto the next item. 它不会引发异常,它只是下载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);
        }
    }

To start, try switching from HttpWebRequest to FtpWebRequest. 首先,尝试从HttpWebRequest切换到FtpWebRequest。 Not sure if that will make a huge difference, but if you're getting stuff from an FTP it may. 不知道这是否会带来很大的变化,但是如果您从FTP获得内容,可能会有所不同。

I feel like you might change from using a do-while to a while with something like this: 我觉得您可能会从使用do-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);
}

Something else you may consider, maybe just download the file to a stream, then save it to the file after you've already closed the FTP connection. 您可能会考虑的其他方法,也许只是将文件下载到流中,然后在关闭FTP连接后将其保存到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM