Click here to Skip to main content
15,936,349 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,
I have a program that downloads file from FTP Server.
This is my code for downloading files
Dim request As FtpWebRequest = Nothing
    Dim response As FtpWebResponse = Nothing
    request = DirectCast(FtpWebRequest.Create(New Uri(clsDownload(index).FTPURL)), FtpWebRequest)
    request.ServicePoint.ConnectionLimit = maxDownload
    request.Method = WebRequestMethods.Ftp.DownloadFile
    request.UseBinary = True
    request.UsePassive = True
    request.KeepAlive = False
    request.Credentials = New NetworkCredential(username, password)
    response = DirectCast(request.GetResponse(), FtpWebResponse)
    Dim ftpStream As Stream = response.GetResponseStream()

    Dim bufferSize As Integer = 2048
    Dim readCount As Integer
    Dim buffer As Byte() = New Byte(bufferSize - 1) {}
    readCount = ftpStream.Read(buffer, 0, bufferSize)
    While readCount > 0
        outputStream.Write(buffer, 0, readCount)
        readCount = ftpStream.Read(buffer, 0, bufferSize)
    End While

The above code runs fine when the filesize is less than 10MB.
When file is greater than 10MB the program can't download the file.
Well at first the file is downloaded, let say the file is 11000KB the program will download the file to 10999 the last 1KB causes error... don't know whats wrong with my code.

This is the error
The underlying connection was closed: An unexpected error occurred on a receive.

I just try using different bufferSize(1000, 32 * 1024) but same error occured...
Updated 27-Jun-12 3:07am
Bernhard Hiller 27-Jun-12 6:40am    
Did you check that the file on the server is OK (e.g. by downloading with Internet Explorer)?
How do you know that the downloaded file is not OK? Do you get any error messages?
Does that behavior also happen with a larger bufferSize (e.g. 1048576)?
hansoctantan 27-Jun-12 8:05am    
I will try it...
hansoctantan 27-Jun-12 8:09am    
and yes I get a runtime error
hansoctantan 27-Jun-12 8:14am    
Yes it successfully downloaded the file in mozilla browser manually...

Check this question might help you-
Download large file from FTP C#[^]
Share this answer
string[] files ={ "UserList.csv", "Catalog.csv", "DeleteUser.csv" };

                Sftp sftp = new Sftp(ftpServerIPAndPort, ftpUserName, decryptor(ftpPassword));

                foreach (string filename in files)
                   sftp.Get(ftpRootFolder + filename, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Ayush\CSVFilesBackup/" + filename);

This Example Fetch these three files from SFTP of any size........... Try This
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900