這是代碼:爲什麼我收到異常:ObjectDisposedException?
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);
唯一的例外是上線:
int bytesRead = responseStream.Read(buffer, 0, Length);
,如果我不使用的StreamReader長和關閉它的正常工作,但一旦我加入StreamReader我收到異常。
無法訪問處置的對象。
對象名稱:'System.Net.Sockets.NetworkStream'。 284
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:
線是:
int bytesRead = responseStream.Read(buffer, 0, Length);
有辦法做某事嗎?用StreamReader讀取文件大小而不處理流?我的ftp服務器不允許我使用ContentLength,所以我嘗試使用StreamReader,而StreamReader確實獲得了文件大小,但也做出了處理。 – 2014-12-10 22:54:46
你應該使用'using'並且在''using'塊內部做你想要的,所以之後資源被自動處置 http://msdn.microsoft.com/en-us/library/yh598w02.aspx – dotctor 2014-12-10 22:59:09
你是將運行到一個更大的問題,以獲得您在整個流中讀取的總長度,但似乎您正在嘗試爲讀取設置進度條。如果你只是等待整個下載時間來確定你的進度條應該有多大,那麼進度條有什麼意義呢? – 2014-12-10 22:59:49