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

时间:2015-08-07 13:57:23

标签: c# download ftp httpwebrequest

以下是从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);
        }
    }

1 个答案:

答案 0 :(得分:0)

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

我觉得你可能会因为使用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);
}

您可以考虑的其他内容,可能只是将文件下载到流中,然后在您已经关闭FTP连接后将其保存到文件中。