Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am trying to download all the files from the ftp server,it showing this error

Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream..and this is my code

VB
Dim filepath As String = "D:\transfer"
       Dim ftp As FtpWebRequest = DirectCast(WebRequest.Create("ftp://611.161.182.215/RPT/"), FtpWebRequest)
       ftp.Method = WebRequestMethods.Ftp.ListDirectory
       Dim ftpFiles As New ArrayList()
       ftp.Credentials = New NetworkCredential("admin", "12345")
       ftp.KeepAlive = True
       Dim Response As FtpWebResponse = ftp.GetResponse()
       Dim responseStream As Stream = Response.GetResponseStream()
       Dim reader = New StreamReader(responseStream)
       While Not (reader.EndOfStream)
           ftpFiles.Add(reader.ReadLine())
           'ListBox1.Items.Add(ftpFiles.ToString())
       End While
       For Each file In ftpFiles
           Dim a As String = file
           ' ListBox1.Items.Add(file)
           Dim outputStream As New FileStream(filepath + "\" + a, FileMode.Create)

           Response = DirectCast(ftp.GetResponse(), FtpWebResponse)
           responseStream = Response.GetResponseStream()

           Dim cl As Long = Response.ContentLength
           Dim bufferSize As Integer = 2048
           Dim readCount As Integer
           'ftp.KeepAlive = True


           Dim buffer As Byte() = New Byte(bufferSize - 1) {}
           readCount = responseStream.Read(buffer, 0, bufferSize)
           While readCount > 0
               outputStream.Write(buffer, 0, readCount)
               readCount = responseStream.Read(buffer, 0, bufferSize)
           End While
           responseStream.Close()
           outputStream.Close()
           response.Close()
           MsgBox("success")
       Next

   End Sub
Posted
Comments
Sergey Alexandrovich Kryukov 15-Oct-13 1:40am    
In what line? Anyway, the exception is self-explanatory. Don't try to use the stream after it was disposed. Use the debugger, and you will see where the exception is thrown.
—SA
rifayee 15-Oct-13 1:44am    
this line is showing the error
readCount = responseStream.Read(buffer, 0, bufferSize)
Sergey Alexandrovich Kryukov 15-Oct-13 2:11am    
Solution 2 points out a bug...
—SA

1 solution

Move the line:
response.Close()
outside the For loop...
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 15-Oct-13 2:10am    
Good catch, 5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900