Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
You can use a Using block to guarantee that the system disposes of a resource when your code exits the block. This is useful if you are using a system resource that consumes a large amount of memory, or that other components also want to use.
To dispose of a file stream when your code is finished with it
Make sure you include the appropriate Imports Statement (.NET Namespace and Type) for the file stream at the beginning of your source file (in this case, System.IO).
Create a
Usingblock with theUsingandEnd Usingstatements. Inside the block, put the code that deals with the file stream.Declare the stream and create an instance of it as part of the
Usingstatement.' Insert the following line at the beginning of your source file. Imports System.IO Public Sub AccessFile(ByVal s As String) Using fs As New StreamReader(s) MsgBox("reading file contents """ & fs.ReadToEnd() & """") End Using End SubThe system disposes of the resource no matter how you exit the block, including the case of an unhandled exception.
Note that you cannot access
fsfrom outside theUsingblock, because its scope is limited to the block.You can use this same technique on a system resource such as a SQL database connection or a COM wrapper. You use a
Usingblock when you want to be sure to leave the resource available for other components after you have exited theUsingblock.