FTP文件(.csv)下载被截断

时间:2013-07-30 18:22:11

标签: ftp download ftpwebrequest

使用FTP下载.csv文件。该文件在服务器上是46k。当我下载时,它会被截断为44k。我不知道为什么......当我在Excel中查看数据时,它被缩短了。我将缓冲区增加到4096但没有骰子(这可能不是问题)。

我最初抓住了以下代码,并从Downloading Files Using FTPWebRequest

调整了它

任何想法都赞赏!感谢。

    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, false);
        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);
        }
    }

    private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive)
    {
        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;
    }

1 个答案:

答案 0 :(得分:2)

尝试这种方法:

private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{ 
    int Length = 2048;
    Byte[] buffer = new Byte[Length];
    int bytesRead = responseStream.Read(buffer, 0, Length);     

    FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, false);
    request.Method = WebRequestMethods.Ftp.DownloadFile;

    Stream reader = request.GetResponse().GetResponseStream();
    FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);

    while (bytesRead > 0)
            {
        //if (bytesRead == 0)
          //  break;
                bytesRead = responseStream.Read(buffer, 0, Length);
                fileStream.Write(buffer, 0, bytesRead);
            }

         fileStream.Close();
}