为什么我收到异常:ObjectDisposedException? [英] Why i'm getting exception: ObjectDisposedException?
问题描述
这是代码:
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);
如果我没有使用StreamReader,并且关闭它工作正常,但是一旦我添加StreamReader我收到了异常。
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.
对象名称:' System.Net.Sockets.NetworkStream'。
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:
第284行是:
Line 284 is:
int bytesRead = responseStream.Read(buffer, 0, Length);
推荐答案
ObjectDisposedException :操作时引发的异常是在处理过的对象上执行的。
ObjectDisposedException: The exception that is thrown when an operation is performed on a disposed object.
当您关闭 readStream
readStream.Close();
StreamReader.Close方法关闭StreamReader对象和基础流,并发布任何与读者相关的系统资源。 Close的这个实现调用Dispose方法传递一个真实值。
StreamReader.Close Method Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader. This implementation of Close calls the Dispose method passing a true value.
底层 responseStream
the underlying responseStream
which is set in
StreamReader readStream = new StreamReader(responseStream, ...
关闭并关闭一个流调用的dispose方法,然后它被抛弃,之后你访问 responseStream
和boom! ObjectDisposedException
is closed and closing a stream call dispose method and it get disposed. after that you access responseStream
and boom! ObjectDisposedException
这篇关于为什么我收到异常:ObjectDisposedException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!