0

我试图在计时器中执行 FTPWEBREQUEST,但出现此错误TextBox1.Text = reader.ReadToEnd

Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'. 

你能帮我吗?

谢谢

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        Timer1.Stop()

        Dim request As FtpWebRequest = CType(WebRequest.Create(""), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails

        request.Credentials = New NetworkCredential("", "")
        Dim response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)

        Dim ResponseStream As Stream = response.GetResponseStream()
        Dim reader As New StreamReader(ResponseStream)

        'Console.Write(reader.ReadToEnd)
        'MessageBox.Show("Directory List Complete, status {0}", response.StatusDescription)


        'MessageBox.Show(reader.ReadToEnd)
        'MessageBox.Show(reader.ReadToEnd)

        TextBox1.Text = reader.ReadToEnd
        TextBox1.Text = vbNewLine
        TextBox1.Text = vbNewLine

        ResponseStream.Close()
        reader.Close()

        response.Close()






        reader.Close()
        response.Close()


        Timer1.Start()

    End Sub
End Class
4

1 回答 1

1

我不确切知道您的目标以及为什么需要计时器。

但我想给你一些编码练习的建议:

您不应该关闭(处置)您的流两次。使用该Using语句以获得更干净和可读的代码。它还有助于尽早释放资源,即使抛出异常。

Public Class Form1    

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    

    End Sub    

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick    

        Timer1.Stop()    

         Dim request As FtpWebRequest = CType(WebRequest.Create(""), FtpWebRequest)
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails

        request.Credentials = New NetworkCredential("", "")
        Using response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)

            Using responseStream As Stream = response.GetResponseStream()
                Using reader As New StreamReader(responseStream)


                    TextBox1.Text = reader.ReadToEnd
                    TextBox1.Text += vbNewLine 
                    TextBox1.Text += vbNewLine
                    ' Use the + for appending (set the textbox to multiline)

                End Using

            End Using

        End Using    

        Timer1.Start()    

    End Sub    
End Class 
于 2012-10-23T17:12:22.503 回答