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

FTP文件(.csv)下载被截断,ftp,download,ftpwebrequest,Ftp,Download,Ftpwebrequest,这将使用FTP下载.csv文件。服务器上的文件为46k。当我下载时,它被截断为44k。我不知道为什么。。。当我在Excel中查看数据时,它会被截短。我将缓冲区增加到4096,但没有骰子(这可能不是问题) 我最初获取了以下代码并对其进行了调整: 任何想法都很感激!谢谢 private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFil

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

我最初获取了以下代码并对其进行了调整:

任何想法都很感激!谢谢

    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;
    }
尝试以下方法:

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

始终使用记事本查看CSV文件,并将binary设置为False如果在while循环之后添加fileStream.Close(),会发生什么?或者,如果您将缓冲区设置得太大,以至于整个文件都可以一次读取?@rene>fileStream.Close()工作正常!好极了。。。如果可以,我会接受你的回答,但我想我们不能接受评论。。。谢谢谢谢你,伙计。我缺少fileStream.Close(),这导致截断。。。“while”逻辑实际上还可以。。。