This is the code:
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
long filel = readStream.ReadToEnd().Length;
readStream.Close();
FileStream writeStream = new FileStream(ftpdirectories + "\\" + filenameonly, FileMode.Create);
string fnn = ftpdirectories + "\\" + filenameonly;
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
The exception is on the line:
int bytesRead = responseStream.Read(buffer, 0, Length);
If i'm not using the StreamReader the long and the Close it's working fine but once i'm adding the StreamReader i'm getting the exception.
Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
System.ObjectDisposedException was caught
HResult=-2146232798
Message=Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
Source=System
ObjectName=System.Net.Sockets.NetworkStream
StackTrace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.FtpDataStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at FTP_ProgressBar.FtpProgress.DownloadFtpContent(Object sender, String file, String filesdirectories, String fn) in c:\ftp_progressbar\FTP_ProgressBar\FtpProgress.cs:line 284
InnerException:
Line 284 is:
int bytesRead = responseStream.Read(buffer, 0, Length);
You using..
Provide encoding required for response as follows.
This happens with German characters like ü, ö, ä etc. So probably UTF-8 fails while reading and closes the stream. Hence, you need to maintain encoding list against URLs or expected response and pass it as above.
when you close
readStream
the underlying
responseStream
which is set inis closed and closing a stream call dispose method and it get disposed. after that you access
responseStream
and boom!ObjectDisposedException
The
Stream
gets closed and disposed when theStreamReader
gets closed. Check out the MSDN page on theStreamReader
Close method for more information.To wit, the
StreamReader
's Close methodAlong with that: