Using C# 2005 Express Edition
I'm using the code below to download a file from an ftp site. The code works fine except that an ObjectDisposedException is raised when the last part of the file is read. The exception is.Cannot access a disposed object.
I'm for the moment trapping the error and just ignoring it. Is it the right way to handle this? Most of the samples I've seen on the web don't seem to mention this.
Thanks
Code:string fileToDownload = @"ftp://xxx.xxx.xxx.xxx/sub1/sub2/Images/sub3/00001.tif"; FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(fileToDownload); request.Credentials = c; request.Proxy = null; request.Method = WebRequestMethods.Ftp.DownloadFile; FtpWebResponse response = null; try { response = (FtpWebResponse)request.GetResponse(); ShowAction(string.Format(@"Content length {0}", response.ContentLength)); ShowAction(string.Format(@"StatusCode {0}", response.StatusCode)); ShowAction(string.Format(@"StatusDescription {0}", response.StatusDescription)); } catch (WebException e) { MessageBox.Show(e.ToString()); return; } string localFile = @"c:\junk\abc\00001.tif"; ShowAction("Writing file locally " + localFile); FileStream outFile = new FileStream(localFile, FileMode.Create); BinaryWriter writer = new BinaryWriter(outFile); using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) { ShowAction(string.Format(@"StatusCode {0}", response.StatusCode)); ShowAction(string.Format(@"StatusDescription {0}", response.StatusDescription)); int readBytes = 0; byte[] inData; inData = reader.ReadBytes(512); readBytes = inData.Length; while (readBytes > 0) { writer.Write(inData); writer.Flush(); try { inData = reader.ReadBytes(512); readBytes = inData.Length; } catch (ObjectDisposedException e) { ShowAction("Caught: " + e.Message); ShowAction("Last ReadChars: " + readBytes.ToString()); readBytes = 0; } catch (Exception e1) { ShowAction("Exception on last line. " + e1.ToString()); } } } writer.Close(); this.Cursor = Cursors.Default; response.Close(); ShowAction("Download complete");




Reply With Quote