I want to download file from the ftp server. I have written following code to download file from ftp
public void downloadFile(string FTPAddress, string filename, string username, string password, string destFile)
{
try
{
FtpWebRequest request = FtpWebRequest.Create(FTPAddress + filename) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.UseBinary = true;
request.KeepAlive = false; //close the connection when done
request.Timeout = 60000;
//Streams
using (var response = request.GetResponse())
{
using (Stream reader = response.GetResponseStream())
{
byte[] buffer = new byte[1024];
using (Stream streamFile = File.Create(destFile))
{
while (true)
{
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
streamFile.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
But when running this code giving me exception :
The underlying connection was closed: An unexpected error occurred on a receive.
What can be problem help me...
Suggestion 1 : EXPLICITLY set your timeout to infinite.
request.Timeout = -1;
Suggestion 2: Catch the more specific exception type WebException, and examine the WebExceptionStatus.
Suggestion 3: Turn on tracing for System.Net.
I've set the TraceLevel for two of the sources that aren't applicable in your situation.
How to: Configure Network Tracing
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="includehex" maxdatasize="1024">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Cache">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Http">
<listeners>
<add name="System.Net "/>
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.WebSockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
<add name="System.Net.Cache" value="Off"/>
<add name="System.Net.Http" value="Off"/>
<add name="System.Net.Sockets" value="Verbose"/>
<add name="System.Net.WebSockets" value="Off"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log"
/>
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With