Question

This downloads a .csv file using FTP. The file is 46k on the server. When I download, it gets truncated to 44k. I have no idea why ... when I view the data in Excel, it is cut short. I increased the buffer to 4096 but no dice (this probably isn't the problem).

I originally grabbed the following code and tweaked it from: Downloading Files Using FTPWebRequest

Any thoughts appreciated ! Thanks.

    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;
    }
Était-ce utile?

La solution

Try this approach:

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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top