MY

In older versions of Visual Basic .NET, programmers discovered that many common tasks were difficult to perform. For example, many programs get the name of the user logged on to the computer, read a text file into a string, get the program’s version number, or examine all of the application’s currently loaded forms. Although you could accomplish all of these tasks in early versions of Visual Basic .NET, doing so was awkward.

To make these common tasks easier, the My namespace was introduced to provide shortcuts for basic chores. For example, to read the text in a file in Visual Basic .NET 2003, you must create some sort of object that can work with a file such as a StreamReader, use the object to read the file (the ReadToEnd method for a StreamReader), and then dispose of the object. The following code shows how you might do this in Visual Basic .NET 2003:

Dim stream_reader As New IO.StreamReader(file_name)
Dim file_contents As String = stream_reader.ReadToEnd()
stream_reader.Close()

This isn’t too difficult, but it does seem more complicated than such a simple everyday task should be.

The My namespace provides a simpler method for reading a file’s contents. The My.Computer.FileSystem.ReadAllText method reads a text file in a single statement. The following statement reads the text in the file C:\Temp\Test.txt:

Dim file_contents As String =
    My.Computer.FileSystem.ReadAllText("C:\Temp\Test.txt")

There is nothing new in the My namespace. All the tasks it performs you can already ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.