1

请问三个问题

1) 如果在下面的尝试中出现异常,请求流会自动关闭,因为它在using

2)do I even need the requestStream.Close() and requestStream.Dispose() as it is in a using?

3) 我需要关闭 System.Net.FtpWebRequest 吗?

Try


    Dim rqst As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://1.com/text.txt"), System.Net.FtpWebRequest)
    rqst.Credentials = New System.Net.NetworkCredential("useb", "pass")
    rqst.Method = System.Net.WebRequestMethods.Ftp.UploadFile

    'Throw New ApplicationException("Exception Occured")
    Dim fle() As Byte = System.IO.File.ReadAllBytes("C:\test.txt")

    Using requestStream As Stream = rqst.GetRequestStream()


        requestStream.Write(fle, 0, fle.Length)
        requestStream.Close() 'do I need this?
        requestStream.Dispose() 'do I need this ?

    End Using

Catch ex As Exception

    MessageBox.Show(ex.Message.ToString())

End Try
4

2 回答 2

1

不,如果您正在使用using. 由于using本身是用来处置的。此外,“使用”语句的原因是确保对象始终正确处理,并且不需要显式代码来确保发生这种情况。

当控制流退出 using 块时,立即调用 Dispose 方法。

于 2012-11-02T18:11:41.380 回答
1

是的。如果在 using 语句中执行代码时发生异常,则流将在进入 Catch 块之前被释放。

于 2012-11-02T22:16:52.190 回答