Disposing Streams

StewartBW 505 Reputation points
2024-03-26T15:43:13.7066667+00:00

Hey

I have 2 different usages of Streams, is the first mode neccessary for proper disposing or I can just use the second mode?

Second one: webClient.OpenRead(BaseURL) is fine?

First:
Using data As Stream = webClient.OpenRead(BaseURL)
 Using reader As New StreamReader(data)
  response = reader.ReadToEnd()
 End Using
End Using

vs

Second:
Using reader As New StreamReader(webClient.OpenRead(BaseURL))
 response = reader.ReadToEnd
End Using
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,605 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 49,246 Reputation points
    2024-03-26T15:57:00.1933333+00:00

    Either version works. If you want the simplest form then the second form is simpler. Because StreamReader, by default, takes ownership of the stream then it will automatically close it when the reader is disposed (RAII).

    Note that there is always a chance that the stream is opened and then creating and initializing the reader fails which leaves the stream open but given the reader does almost nothing this is not a realistic issue. But when using the RAII approach this is something to bear in mind.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful