Вы находитесь на странице: 1из 184

My Collection

This document is provided "as-is". Information and views expressed in this document, including URL and other Internet Web site references, may change without
notice. This document does not provide you with any legal rights to any intellectual property in any Microsoft product or product name. You may copy and use
this document for your internal, reference purposes. You may modify this document for your internal, reference purposes. 2013 Microsoft. All rights reserved.
Terms of Use (http://msdn.microsoft.com/cc300389.aspx) | Trademarks (http://www.microsoft.com/library/toolbar/3.0/trademarks/en-us.mspx)
Table Of Contents
Chapter 1

How to: Read From Comma-Delimited Text Files in Visual Basic


How to: Read From Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
How to: Read From Binary Files in Visual Basic
How to: Read Text from Files with a StreamReader (Visual Basic)
Walkthrough: Manipulating Files and Directories in Visual Basic
Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)
Parsing Text Files with the TextFieldParser Object (Visual Basic)
Storing Data to and Reading from the Clipboard (Visual Basic)
Programming in Visual Basic
Reading from Files
Printing and Reporting
Customizing Projects and Extending My
Chapter 1
How to: Read From Comma-Delimited Text Files in Visual Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. The TextFieldType property defines whether it is a delimited
file or one with fixed-width fields of text.

To parse a comma delimited text file

1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")

2. Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the delimiter as ",".

VB

MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")

3. Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops through the file, displaying each field in
turn and reporting any fields that are formatted incorrectly.

VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.

VB

End While
End Using

Example
This example reads from the file test.txt.

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Text Files in Visual Basic
Visual Studio 2012

The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The file encoding can be specified if the contents of the file use an
encoding such as ASCII or UTF-8.

If you are reading from a file with extended characters, you will need to specify the file encoding.

Note

To read a file a single line of text at a time, use the OpenTextFileReader method of the My.Computer.FileSystem object. The OpenTextFileReader method returns a
StreamReader object. You can use the ReadLine method of the StreamReader object to read a file one line at a time. You can test for the end of the file using the
EndOfStream method of the StreamReader object.

To read from a text file

Use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string, supplying the path. The following example
reads the contents of test.txt into a string and then displays it in a message box.

VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

To read from a text file that is encoded

Use the ReadAllText method of the My.Computer.FileSytem object to read the contents of a text file into a string, supplying the path and file encoding type. The
following example reads the contents of the UTF32 file test.txt into a string and then displays it in a message box.

VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt",
System.Text.Encoding.UTF32)
MsgBox(fileReader)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

There is not enough memory to write the string to buffer (OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
FileSystem
ReadAllText
Concepts
File Encodings (Visual Basic)
Other Resources
Reading from Files in Visual Basic

2014 Microsoft. All rights reserved.


How to: Read From Fixed-width Text Files in Visual Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs.

The TextFieldType property defines whether the parsed file is a delimited file or one that has fixed-width fields of text. In a fixed-width text file, the field at the end can
have a variable width. To specify that the field at the end has a variable width, define it to have a width less than or equal to zero.

To parse a fixed-width text file

1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file test.log.

VB

Using Reader As New Microsoft.VisualBasic.


FileIO.TextFieldParser("C:\TestFolder\test.log")

2. Define the TextFieldType property as FixedWidth, defining the width and format. The following code defines the columns of text; the first is 5 characters wide, the
second 10, the third 11, and the fourth is of variable width.

VB

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)

3. Loop through the fields in the file. If any lines are corrupted, report an error and continue parsing.

VB

Dim currentRow As String()


While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.

VB

End While
End Using

Example
This example reads from the file test.log.

VB

Using Reader As New Microsoft.VisualBasic.FileIO.


TextFieldParser("C:\TestFolder\test.log")

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Text Files with Multiple Formats in Visual
Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. You can process a file with multiple formats by using the
PeekChars method to determine the format of each line as you parse through the file.

To parse a text file with multiple formats

1. Add a text file named testfile.txt to your project. Add the following content to the text file.

Err 1001 Cannot access resource.


Err 2014 Resource not found.
Acc 10/03/2009User1 Administrator.
Err 0323 Warning: Invalid access attempt.
Acc 10/03/2009User2 Standard user.
Acc 10/04/2009User2 Standard user.

2. Define the expected format and the format used when an error is reported. The last entry in each array is -1, therefore the last field is assumed to be of variable
width. This occurs when the last entry in the array is less than or equal to 0.

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}

3. Create a new TextFieldParser object, defining the width and format.

VB

Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")


MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat

4. Loop through the rows, testing for format before reading.

VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()

5. Write errors to the console.

VB

Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid.")
End Try
End While
End Using

Example
Following is the complete example that reads from the file testfile.txt.

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat
Dim currentRow As String()
While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()
Catch ex As FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Console.ReadLine()

Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
Reference
TextFieldParser
PeekChars
MalformedLineException
WriteAllText
EndOfData
TextFieldType
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Binary Files in Visual Basic
Visual Studio 2012

The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.

To read from a binary file

Use the ReadAllBytes method, which returns the contents of a file as a byte array. This example reads from the file C:/Documents and
Settings/selfportrait.jpg.

VB

Dim bytes = My.Computer.FileSystem.ReadAllBytes(


"C:/Documents and Settings/selfportrait.jpg")
PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))

For large binary files, you can use the Read method of the FileStream object to read from the file only a specified amount at a time. You can then limit how much of
the file is loaded into memory for each read operation. The following code example copies a file and allows the caller to specify how much of the file is read into
memory per read operation.

VB

' This method does not trap for exceptions. If an exception is


' encountered opening the file to be copied or writing to the
' destination location, then the exception will be thrown to
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
ByVal copyPath As String,
ByVal bufferSize As Integer,
ByVal overwrite As Boolean)

Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then


My.Computer.FileSystem.DeleteFile(copyPath)
End If

' Adjust array length for VB array declaration.


Dim bytes = New Byte(bufferSize - 1) {}

While inputFile.Read(bytes, 0, bufferSize) > 0


My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
End While

inputFile.Close()
End Sub

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

There is not enough memory to write the string to buffer (OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
ReadAllBytes
WriteAllBytes
Other Resources
Reading from Files in Visual Basic
Storing Data to and Reading from the Clipboard (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read Text from Files with a StreamReader (Visual
Basic)
Visual Studio 2012

The My.Computer.FileSystem object provides methods to open a TextReader and a TextWriter. These methods, OpenTextFileWriter and OpenTextFileReader, are
advanced methods that do not appear in IntelliSense unless you select the All tab.

To read a line from a file with a text reader

Use the OpenTextFileReader method to open the TextReader, specifying the file. This example opens the file named testfile.txt, reads a line from it, and
displays the line in a message box.

VB

Dim fileReader As System.IO.StreamReader


fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)

Robust Programming
The file that is read must be a text file.

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

Security
To read from a file, your assembly requires a privilege level granted by the FileIOPermission class. If you are running in a partial-trust context, the code might throw an
exception due to insufficient privileges. For more information, see Code Access Security Basics. The user also needs access to the file. For more information, see ACL
Technology Overview.

See Also
Reference
FileSystem
OpenFileDialog
OpenTextFileWriter
OpenTextFileReader
Other Resources
SaveFileDialog Component (Windows Forms)
Reading from Files in Visual Basic

2014 Microsoft. All rights reserved.


Walkthrough: Manipulating Files and Directories in Visual Basic
Visual Studio 2012

This walkthrough provides an introduction to the fundamentals of file I/O in Visual Basic. It describes how to create a small application that lists and examines text files in a
directory. For each selected text file, the application provides file attributes and the first line of content. There is an option to write information to a log file.

This walkthrough uses members of the My.Computer.FileSystem Object, which are available in Visual Basic. See FileSystem for more information. At the end of the
walkthrough, an equivalent example is provided that uses classes from the System.IO namespace.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that
you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To create the project

1. On the File menu, click New Project.

The New Project dialog box appears.

2. In the Installed Templates pane, expand Visual Basic, and then click Windows. In the Templates pane in the middle, click Windows Forms Application.

3. In the Name box, type FileExplorer to set the project name, and then click OK.

Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.

4. Add the controls in the following table to the form, and set the corresponding values for their properties.

Control Property Value

ListBox Name filesListBox

Button Name browseButton


Text Browse

Button Name examineButton


Text Examine

CheckBox Name saveCheckBox


Text Save Results

FolderBrowserDialog Name FolderBrowserDialog1

To select a folder, and list files in a folder

1. Create a Click event handler for browseButton by double-clicking the control on the form. The Code Editor opens.

2. Add the following code to the Click event handler.

VB

If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then


' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If

The FolderBrowserDialog1.ShowDialog call opens the Browse For Folder dialog box. After the user clicks OK, the SelectedPath property is sent as an argument
to the ListFiles method, which is added in the next step.

3. Add the following ListFiles method.

VB

Private Sub ListFiles(ByVal folderPath As String)


filesListBox.Items.Clear()

Dim fileNames = My.Computer.FileSystem.GetFiles(


folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

For Each fileName As String In fileNames


filesListBox.Items.Add(fileName)
Next
End Sub

This code first clears the ListBox.

The GetFiles method then retrieves a collection of strings, one for each file in the directory. The GetFiles method accepts a search pattern argument to retrieve files
that match a particular pattern. In this example, only files that have the extension .txt are returned.

The strings that are returned by the GetFiles method are then added to the ListBox.

4. Run the application. Click the Browse button. In the Browse For Folder dialog box, browse to a folder that contains .txt files, and then select the folder and click OK.

The ListBox contains a list of .txt files in the selected folder.

5. Stop running the application.

To obtain attributes of a file, and content from a text file

1. Create a Click event handler for examineButton by double-clicking the control on the form.

2. Add the following code to the Click event handler.

VB

If filesListBox.SelectedItem Is Nothing Then


MessageBox.Show("Please select a file.")
Exit Sub
End If

' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString

' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If

' Obtain file information in a string.


Dim fileInfoText As String = GetTextForOutput(filePath)

' Show the file information.


MessageBox.Show(fileInfoText)

The code verifies that an item is selected in the ListBox. It then obtains the file path entry from the ListBox. The FileExists method is used to check whether the file
still exists.

The file path is sent as an argument to the GetTextForOutput method, which is added in the next step. This method returns a string that contains file information.
The file information appears in a MessageBox.

3. Add the following GetTextForOutput method.

VB

Private Function GetTextForOutput(ByVal filePath As String) As String


' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If

' Create a new StringBuilder, which is used


' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()

' Obtain file information.


Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

' Add file attributes.


sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)

' Open the text file.


Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)

' Add the first line from the file.


If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()

Return sb.ToString
End Function

The code uses the GetFileInfo method to obtain file parameters. The file parameters are added to a StringBuilder.
The OpenTextFileReader method reads the file contents into a StreamReader. The first line of the contents is obtained from the StreamReader and is added to the
StringBuilder.

4. Run the application. Click Browse, and browse to a folder that contains .txt files. Click OK.

Select a file in the ListBox, and then click Examine. A MessageBox shows the file information.

5. Stop running the application.

To add a log entry

1. Add the following code to the end of the examineButton_Click event handler.

VB

If saveCheckBox.Checked = True Then


' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

Dim logText As String = "Logged: " & Date.Now.ToString &


vbCrLf & fileInfoText & vbCrLf & vbCrLf

' Append text to the log file.


My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If

The code sets the log file path to put the log file in the same directory as that of the selected file. The text of the log entry is set to the current date and time
followed by the file information.

The WriteAllText method, with the append argument set to True, is used to create the log entry.

2. Run the application. Browse to a text file, select it in the ListBox, select the Save Results check box, and then click Examine. Verify that the log entry is written to the
log.txt file.

3. Stop running the application.

To use the current directory

1. Create an event handler for Form1_Load by double-clicking the form.

2. Add the following code to the event handler.

VB

' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

This code sets the default directory of the folder browser to the current directory.

3. Run the application. When you click Browse the first time, the Browse For Folder dialog box opens to the current directory.

4. Stop running the application.

To selectively enable controls

1. Add the following SetEnabled method.

VB

Private Sub SetEnabled()


Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)

examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub

The SetEnabled method enables or disables controls depending on whether an item is selected in the ListBox.

2. Create a SelectedIndexChanged event handler for filesListBox by double-clicking the ListBox control on the form.

3. Add a call to SetEnabled in the new filesListBox_SelectedIndexChanged event handler.

4. Add a call to SetEnabled at the end of the browseButton_Click event handler.

5. Add a call to SetEnabled at the end of the Form1_Load event handler.

6. Run the application. The Save Results check box and the Examine button are disabled if an item is not selected in the ListBox.
Full example using My.Computer.FileSystem
Following is the complete example.

VB

' This example uses members of the My.Computer.FileSystem


' object, which are available in Visual Basic.

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


' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click


If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If
SetEnabled()
End Sub

Private Sub ListFiles(ByVal folderPath As String)


filesListBox.Items.Clear()

Dim fileNames = My.Computer.FileSystem.GetFiles(


folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

For Each fileName As String In fileNames


filesListBox.Items.Add(fileName)
Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click


If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If

' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString

' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If

' Obtain file information in a string.


Dim fileInfoText As String = GetTextForOutput(filePath)

' Show the file information.


MessageBox.Show(fileInfoText)

If saveCheckBox.Checked = True Then


' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

Dim logText As String = "Logged: " & Date.Now.ToString &


vbCrLf & fileInfoText & vbCrLf & vbCrLf

' Append text to the log file.


My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String


' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If

' Create a new StringBuilder, which is used


' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()

' Obtain file information.


Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

' Add file attributes.


sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)

' Open the text file.


Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)

' Add the first line from the file.


If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()

Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChang


SetEnabled()
End Sub

Private Sub SetEnabled()


Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)

examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub

Full example using System.IO


The following equivalent example uses classes from the System.IO namespace instead of using My.Computer.FileSystem objects.

VB

' This example uses classes from the System.IO namespace.

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


' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath =
System.IO.Directory.GetCurrentDirectory()

SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click


If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
SetEnabled()
End If
End Sub

Private Sub ListFiles(ByVal folderPath As String)


filesListBox.Items.Clear()

Dim fileNames As String() =


System.IO.Directory.GetFiles(folderPath,
"*.txt", System.IO.SearchOption.TopDirectoryOnly)

For Each fileName As String In fileNames


filesListBox.Items.Add(fileName)
Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click


If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If

' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString

' Verify that the file was not removed since the
' Browse button was clicked.
If System.IO.File.Exists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If

' Obtain file information in a string.


Dim fileInfoText As String = GetTextForOutput(filePath)

' Show the file information.


MessageBox.Show(fileInfoText)

If saveCheckBox.Checked = True Then


' Place the log file in the same folder as the examined file.
Dim logFolder As String =
System.IO.Path.GetDirectoryName(filePath)
Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")

' Append text to the log file.


Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf

System.IO.File.AppendAllText(logFilePath, logText)
End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String


' Verify that the file exists.
If System.IO.File.Exists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If

' Create a new StringBuilder, which is used


' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()

' Obtain file information.


Dim thisFile As New System.IO.FileInfo(filePath)

' Add file attributes.


sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)

' Open the text file.


Dim sr As System.IO.StreamReader =
System.IO.File.OpenText(filePath)

' Add the first line from the file.


If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()

Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged


SetEnabled()
End Sub

Private Sub SetEnabled()


Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)

examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub

See Also
Tasks
Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)
Reference
System.IO
FileSystem
CurrentDirectory

2014 Microsoft. All rights reserved.


Walkthrough: Manipulating Files by Using .NET Framework
Methods (Visual Basic)
Visual Studio 2012

This walkthrough demonstrates how to open and read a file using the StreamReader class, check to see if a file is being accessed, search for a string within a file read with
an instance of the StreamReader class, and write to a file using the StreamWriter class.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that
you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Creating the Application


Start Visual Studio and begin the project by creating a form that the user can use to write to the designated file.

To create the project

1. On the File menu, select New Project.

2. In the New Project pane, click Windows Application.

3. In the Name box type MyDiary and click OK.

Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.

4. Add the controls in the following table to the form and set the corresponding values for their properties.

Object Properties Value

Button Name Submit


Text Submit Entry

Button Name Clear


Text Clear Entry

TextBox Name Entry


Text Please enter something.
Multiline False

Writing to the File


To add the ability to write to a file via the application, use the StreamWriter class. StreamWriter is designed for character output in a particular encoding, whereas the
Stream class is designed for byte input and output. Use StreamWriter for writing lines of information to a standard text file. For more information on the StreamWriter
class, see StreamWriter.

To add writing functionality

1. From the View menu, choose Code to open the Code Editor.

2. Because the application references the System.IO namespace, add the following statements at the very beginning of your code, before the class declaration for
the form, which begins Public Class Form1.

VB

Imports System
Imports System.IO

Before writing to the file, you must create an instance of a StreamWriter class.

3. From the View menu, choose Designer to return to the Windows Forms Designer. Double-click the Submit button to create a Click event handler for the button,
and then add the following code.

VB

Dim fw As StreamWriter

Note

The Visual Studio Integrated Development Environment (IDE) will return to the Code Editor and position the insertion point within the event handler where you should
add the code.
1. To write to the file, use the Write method of the StreamWriter class. Add the following code directly after Dim fw As StreamWriter. You do not need to worry
that an exception will be thrown if the file is not found, because it will be created if it does not already exist.

VB

Dim ReadString As String


Try
'Pass the file path and name to the StreamWriter constructor.
'Indicate that Append is True, so file will not be overwritten.
fw = New StreamWriter("C:\MyDiary.txt", True)
ReadString = Entry.Text
fw.WriteLine(ReadString)
Finally
'Close the file.
fw.Close()
End Try

2. Make sure that the user cannot submit a blank entry by adding the following code directly after Dim ReadString As String.

VB

If (Entry.Text = "" Or Entry.Text = "Please enter something.") Then


Entry.Text = "Please enter something."
Return
End If

3. Because this is a diary, the user will want to assign a date to each entry. Insert the following code after fw = New StreamWriter("C:\MyDiary.txt", True) to
set the variable Today to the current date.

VB

Dim Today As DateTime


Today = Now
fw.Write(CStr(Today))
fw.Write(ControlChars.CrLf)

4. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.

VB

Entry.Text = ""

Adding Display Features to the Diary


In this section, you add a feature that displays the latest entry in the DisplayEntry TextBox. You can also add a ComboBox that displays various entries and from which
a user can select an entry to display in the DisplayEntry TextBox. An instance of the StreamReader class reads from MyDiary.txt. Like the StreamWriter class,
StreamReader is intended for use with text files.

For this section of the walkthrough, add the controls in the following table to the form and set the corresponding values for their properties.

Control Properties Values

TextBox Name DisplayEntry


Visible False
Size 120,60
Multiline True

Button Name Display


Text Display

Button Name GetEntries


Text Get Entries

ComboBox Name PickEntries


Text Select an Entry
Enabled False

To populate the combo box

1. The PickEntries ComboBox is used to display the dates on which a user submits each entry, so the user can select an entry from a specific date. Create a Click
event handler to the GetEntries button and add the following code.

VB

Dim fr As StreamReader = Nothing


Dim FileString As String
FileString = ""
Try
fr = New System.IO.StreamReader("C:\MyDiary.txt")
PickEntries.Items.Clear()
PickEntries.Enabled = True
Do
FileString = fr.ReadLine
If IsDate(FileString) Then
PickEntries.Items.Add(FileString)
End If
Loop Until (FileString Is Nothing)
Finally
If fr IsNot Nothing Then
fr.Close()
End If
End Try
PickEntries.Enabled = True

2. To test your code, press F5 to compile the application, and then click Get Entries. Click the drop-down arrow in the ComboBox to display the entry dates.

To choose and display individual entries

1. Create a Click event handler for the Display button and add the following code.

VB

Dim fr As StreamReader
Dim ReadString As String
'Make sure ReadString begins empty.
ReadString = ""
Dim FileString As String
fr = New StreamReader("C:\MyDiary.txt")
'If no entry has been selected, show the whole file.
If PickEntries.Enabled = False Or PickEntries.SelectedText Is Nothing Then
Do
'Read a line from the file into FileString.
FileString = fr.ReadLine
'add it to ReadString
ReadString = ReadString & ControlChars.CrLf & FileString
Loop Until (FileString = Nothing)
Else
'An entry has been selected, find the line that matches.
Do

FileString = fr.ReadLine
Loop Until FileString = CStr(PickEntries.SelectedItem)
FileString = CStr(PickEntries.SelectedItem) & ControlChars.CrLf
ReadString = FileString & fr.ReadLine

'Read from the file until EOF or another Date is found.


Do Until ((fr.Peek < 0) Or (IsDate(fr.ReadLine)))
ReadString = ReadString & fr.ReadLine
Loop
End If
fr.Close()
DisplayEntry.Visible = True
DisplayEntry.Text = ReadString

2. To test your code, press F5 to compile the application, and then submit an entry. Click Get Entries, select an entry from the ComboBox, and then click Display.
The contents of the selected entry appear in the DisplayEntry TextBox.

Enabling Users to Delete or Modify Entries


Finally, you can include additional functionality enables users to delete or modify an entry by using DeleteEntry and EditEntry buttons. Both buttons remain disabled
unless an entry is displayed.

Add the controls in the following table to the form and set the corresponding values for their properties.

Control Properties Values

Button Name DeleteEntry


Text Delete Entry
Enabled False

Button Name EditEntry


Text Edit Entry
Enabled False

Button Name SubmitEdit


Text Submit Edit
Enabled False
To enable deletion and modification of entries

1. Add the following code to the Display button's Click event, after DisplayEntry.Text = ReadString.

VB

DeleteEntry.enabled = True

2. Create a Click event handler for the DeleteEntry button and add the following code.

VB

Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
Dim ConfirmDelete As MsgBoxResult
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
' Read through the textfile
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, "")
fr.Close()
' Check to make sure the user wishes to delete the entry
ConfirmDelete = MsgBox("Do you really wish to delete this entry?",
MsgBoxStyle.OKCancel)
If ConfirmDelete = MsgBoxResult.OK Then
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
' Reset controls on the form
DisplayEntry.Text = ""
PickEntries.Text = ""
PickEntries.Items.Clear()
PickEntries.Enabled = False
DeleteEntry.Enabled = False
End If

3. When a user displays an entry, the EditEntry button becomes enabled. Add the following code to the Click event of the Display button after
DisplayEntry.Text = ReadString.

VB

EditEntry.Enabled = True

4. Create a Click event handler for the EditEntry button and add the following code.

VB

Entry.Text = DisplayEntry.Text
SubmitEdit.Enabled = True

5. Create a Click event handler for the SubmitEdit button and add the following code

VB

Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
If Entry.Text = "" Then
MsgBox("Use Delete to Delete an Entry")
Return
End If
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, Entry.Text)
fr.Close()
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
DisplayEntry.Text = Entry.Text
Entry.Text = ""
EditEntry.Enabled = False
SubmitEdit.Enabled = False

To test your code, press F5 to compile the application. Click Get Entries, select an entry, and then click Display. The entry appears in the DisplayEntry TextBox. Click
Edit Entry. The entry appears in the Entry TextBox. Edit the entry in the Entry TextBox and click Submit Edit. Open the MyDiary.txt file to confirm your correction.
Now select an entry and click Delete Entry. When the MessageBox requests confirmation, click OK. Close the application and open MyDiary.txt to confirm the deletion.

See Also
Reference
StreamReader
StreamWriter
Other Resources
Visual Basic Language Walkthroughs

2014 Microsoft. All rights reserved.


Parsing Text Files with the TextFieldParser Object (Visual Basic)
Visual Studio 2012

The TextFieldParser object allows you to parse and process very large file that are structured as delimited-width columns of text, such as log files or legacy database
information. Parsing a text file with TextFieldParser is similar to iterating over a text file, while the parse method to extract fields of text is similar to string manipulation
methods used to tokenize delimited strings.

Parsing Different Types of Text Files


Text files may have fields of various width, delimited by a character such as a comma or a tab space. Define TextFieldType and the delimiter, as in the following
example, which uses the SetDelimiters method to define a tab-delimited text file:

VB

testReader.SetDelimiters(vbTab)

Other text files may have field widths that are fixed. In such cases, you need to define the TextFieldType as FixedWidth and define the widths of each field, as in the
following example. This example uses the SetFieldWidths method to define the columns of text: the first column is 5 characters wide, the second is 10, the third is 11,
and the fourth is of variable width.

VB

testReader.SetFieldWidths(5, 10, 11, -1)


testReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth

Once the format is defined, you can loop through the file, using the ReadFields method to process each line in turn.

If a field does not match the specified format, a MalformedLineException exception is thrown. When such exceptions are thrown, the ErrorLine and ErrorLineNumber
properties hold the text causing the exception and the line number of that text.

Parsing Files with Multiple Formats


The PeekChars method of the TextFieldParser object can be used to check each field before reading it, allowing you to define multiple formats for the fields and react
accordingly. For more information, see How to: Read From Text Files with Multiple Formats in Visual Basic.

See Also
Tasks
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
OpenTextFieldParser
TextFieldParser
PeekChars
ReadFields
CommentTokens
Delimiters
ErrorLine
ErrorLineNumber
FieldWidths
HasFieldsEnclosedInQuotes
LineNumber
TextFieldType
TrimWhiteSpace
SetDelimiters
SetFieldWidths

2014 Microsoft. All rights reserved.


Storing Data to and Reading from the Clipboard (Visual Basic)
Visual Studio 2012

The Clipboard can be used to store data, such as text and images. Because the Clipboard is shared by all active processes, it can be used to transfer data between them.
The My.Computer.Clipboard object allows you to easily access the Clipboard and to read from and write to it.

Reading from the Clipboard


Use the GetText method to read the text in the Clipboard. The following code reads the text and displays it in a message box. There must be text stored on the
Clipboard for the example to run correctly.

VB

MsgBox(My.Computer.Clipboard.GetText())

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms Applications > Clipboard. For more
information, see Code Snippets.

Use the GetImage method to retrieve an image from the Clipboard. This example checks to see if there is an image on the Clipboard before retrieving it and assigning it
to PictureBox1.

VB

If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture As System.Drawing.Image
grabpicture = My.Computer.Clipboard.GetImage()
picturebox1.Image = grabpicture
End If

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms Applications > Clipboard.For more
information, see Code Snippets.

Items placed on the Clipboard will persist even after the application is shut down.

Determining the type of file stored in the Clipboard


Data on the Clipboard may take a number of different forms, such as text, an audio file, or an image. In order to determine what sort of file is on the Clipboard, you can
use methods such as ContainsAudio, ContainsFileDropList, ContainsImage, and ContainsText. The ContainsData method can be used if you have a custom format that
you want to check.

Use the ContainsImage function to determine whether the data contained on the Clipboard is an image. The following code checks to see whether the data is an image
and reports accordingly.

VB

If My.Computer.Clipboard.ContainsImage() Then
MsgBox("Clipboard contains an image.")
Else
MsgBox("Clipboard does not contain an image.")
End If

Clearing the Clipboard


The Clear method clears the Clipboard. Because the Clipboard is shared by other processes, clearing it may have an impact on those processes.

The following code shows how to use the Clear method.

VB

My.Computer.Clipboard.Clear()

Writing to the Clipboard


Use the SetText method to write text to the Clipboard. The following code writes the string "This is a test string" to the Clipboard.

VB

My.Computer.Clipboard.SetText("This is a test string.")


The SetText method can accept a format parameter that contains a type of TextDataFormat. The following code writes the string "This is a test string" to the Clipboard
as RTF text.

VB

My.Computer.Clipboard.SetText("This is a test string.",


System.Windows.Forms.TextDataFormat.Rtf)

Use the SetData method to write data to the Clipboard. This example writes the DataObject dataChunk to the Clipboard in the custom format specialFormat.

VB

My.Computer.Clipboard.SetData("specialFormat", dataChunk)

Use the SetAudio method to write audio data to the Clipboard. This example creates the byte array musicReader, reads the file cool.wav into it, and then writes it to the
Clipboard.

VB

Dim musicReader = My.Computer.FileSystem.ReadAllBytes("cool.wav")


My.Computer.Clipboard.SetAudio(musicReader)

Security Note

Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or confidential data.

See Also
Tasks
How to: Read Object Data from an XML File (C# and Visual Basic)
How to: Write Object Data to an XML File (C# and Visual Basic)
Reference
ClipboardProxy
GetAudioStream
SetDataObject

2014 Microsoft. All rights reserved.


Programming in Visual Basic
Visual Studio 2012

This section discusses programming tasks that you may want to learn more about as you create your Visual Basic application.

In This Section
Accessing Computer Resources (Visual Basic)
Contains documentation on how to use the My.Computer object to access information about the computer on which an application runs and how to control the
computer.

Logging Information from the Application (Visual Basic)


Contains documentation on how to log information from your application using the My.Application.Log and My.Log objects, and how to extend the
application's logging capabilities.

Accessing User Data (Visual Basic)


Contains documentation on tasks that you can accomplish using the My.User object.

Accessing Application Forms (Visual Basic)


Contains documentation on accessing an application's forms by using the My.Forms and My.Application objects.

Accessing Application Web Services (Visual Basic)


Contains documentation on how to access the Web services referenced by the application using the My.WebServices object.

Accessing Application Settings (Visual Basic)


Contains documentation on accessing an application's settings using the My.Settings object.

Processing Drives, Directories, and Files (Visual Basic)


Contains documentation on how to access the file system using the My.Computer.FileSystem object.

See Also
Other Resources
Visual Basic Language Features
Programming Concepts
Collections (C# and Visual Basic)
Developing Applications with Visual Basic

2014 Microsoft. All rights reserved.


Accessing Computer Resources (Visual Basic)
Visual Studio 2012

The My.Computer object is one of the three central objects in My, providing access to information and commonly used functionality. My.Computer provides methods,
properties, and events for accessing the computer on which the application is running. Its objects include:

Audio

Clipboard (ClipboardProxy)

Clock

FileSystem

Info

Keyboard

Mouse

Network

Ports

Registry (RegistryProxy)

In This Section
Playing Sounds (Visual Basic)
Lists tasks associated with My.Computer.Audio, such as playing a sound in the background.

Storing Data to and Reading from the Clipboard (Visual Basic)


Lists tasks associated with My.Computer.Clipboard, such as reading data from or writing data to the Clipboard.

Getting Information about the Computer (Visual Basic)


Lists tasks associated with My.Computer.Info, such as determining a computer's full name or IP addresses.

Accessing the Keyboard (Visual Basic)


Lists tasks associated with My.Computer.Keyboard, such as determining whether CAPS LOCK is on.

Accessing the Mouse (Visual Basic)


Lists tasks associated with My.Computer.Mouse, such as determining whether a mouse is present.

Performing Network Operations (Visual Basic)


Lists tasks associated with My.Computer.Network, such as uploading or downloading files.

Accessing the Computer's Ports (Visual Basic)


Lists tasks associated with My.Computer.Ports, such as showing available serial ports or sending strings to serial ports.

Reading from and Writing to the Registry (Visual Basic)


Lists tasks associated with My.Computer.Registry, such as reading data from or writing data to registry keys.

2014 Microsoft. All rights reserved.


Playing Sounds (Visual Basic)
Visual Studio 2012

The My.Computer.Audio object provides methods for playing sounds.

Playing Sounds
Background playing lets the application execute other code while the sound plays. The My.Computer.Audio.Play method allows the application to play only one
background sound at a time; when the application plays a new background sound, it stops playing the previous background sound. You can also play a sound and wait
for it to complete.

In the following example, the My.Computer.Audio.Play method plays a sound. When AudioPlayMode.WaitToComplete is specified, My.Computer.Audio.Play waits
until the sound completes before calling code continues. When using this example, you should ensure that the file name refers to a .wav sound file that is on your
computer

VB

Sub PlayBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav",
AudioPlayMode.WaitToComplete)
End Sub

In the following example, the My.Computer.Audio.Play method plays a sound. When using this example, you should ensure that the application resources include a
.wav sound file that is named Waterfall.

VB

Sub PlayBackgroundSoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall,
AudioPlayMode.WaitToComplete)
End Sub

Playing Looping Sounds


In the following example, the My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.BackgroundLoop is specified. When
using this example, you should ensure that the file name refers to a .wav sound file that is on your computer.

VB

Sub PlayLoopingBackgroundSoundFile()
My.Computer.Audio.Play("C:\Waterfall.wav",
AudioPlayMode.BackgroundLoop)
End Sub

In the following example, the My.Computer.Audio.Play method plays the specified sound in the background when PlayMode.BackgroundLoop is specified. When
using this example, you should ensure that the application resources include a .wav sound file that is named Waterfall.

VB

Sub PlayLoopingBackgroundSoundResource()
My.Computer.Audio.Play(My.Resources.Waterfall,
AudioPlayMode.BackgroundLoop)
End Sub

The preceding code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms Applications > Sound. For
more information, see Code Snippets.

In general, when an application plays a looping sound, it should eventually stop the sound.

Stopping the Playing of Sounds in the Background


Use the My.Computer.Audio.Stop method to stop the application's currently playing background or looping sound.

In general, when an application plays a looping sound, it should stop the sound at some point.

The following example stops a sound that is playing in the background.

VB

Sub StopBackgroundSound()
My.Computer.Audio.Stop()
End Sub
The preceding code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms Applications > Sound. For
more information, see Code Snippets.

Playing System Sounds


Use the My.Computer.Audio.PlaySystemSound method to play the specified system sound.

The My.Computer.Audio.PlaySystemSound method takes as a parameter one of the shared members from the SystemSound class. The system sound Asterisk
generally denotes errors.

The following example uses the My.Computer.Audio.PlaySystemSound method to play a system sound.

VB

Sub PlaySystemSound()
My.Computer.Audio.PlaySystemSound(
System.Media.SystemSounds.Asterisk)
End Sub

See Also
Reference
Audio
Play
PlaySystemSound
Stop
AudioPlayMode

2014 Microsoft. All rights reserved.


Storing Data to and Reading from the Clipboard (Visual Basic)
Visual Studio 2012

The Clipboard can be used to store data, such as text and images. Because the Clipboard is shared by all active processes, it can be used to transfer data between them.
The My.Computer.Clipboard object allows you to easily access the Clipboard and to read from and write to it.

Reading from the Clipboard


Use the GetText method to read the text in the Clipboard. The following code reads the text and displays it in a message box. There must be text stored on the
Clipboard for the example to run correctly.

VB

MsgBox(My.Computer.Clipboard.GetText())

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms Applications > Clipboard. For more
information, see Code Snippets.

Use the GetImage method to retrieve an image from the Clipboard. This example checks to see if there is an image on the Clipboard before retrieving it and assigning it
to PictureBox1.

VB

If My.Computer.Clipboard.ContainsImage() Then
Dim grabpicture As System.Drawing.Image
grabpicture = My.Computer.Clipboard.GetImage()
picturebox1.Image = grabpicture
End If

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Forms Applications > Clipboard.For more
information, see Code Snippets.

Items placed on the Clipboard will persist even after the application is shut down.

Determining the type of file stored in the Clipboard


Data on the Clipboard may take a number of different forms, such as text, an audio file, or an image. In order to determine what sort of file is on the Clipboard, you can
use methods such as ContainsAudio, ContainsFileDropList, ContainsImage, and ContainsText. The ContainsData method can be used if you have a custom format that
you want to check.

Use the ContainsImage function to determine whether the data contained on the Clipboard is an image. The following code checks to see whether the data is an image
and reports accordingly.

VB

If My.Computer.Clipboard.ContainsImage() Then
MsgBox("Clipboard contains an image.")
Else
MsgBox("Clipboard does not contain an image.")
End If

Clearing the Clipboard


The Clear method clears the Clipboard. Because the Clipboard is shared by other processes, clearing it may have an impact on those processes.

The following code shows how to use the Clear method.

VB

My.Computer.Clipboard.Clear()

Writing to the Clipboard


Use the SetText method to write text to the Clipboard. The following code writes the string "This is a test string" to the Clipboard.

VB

My.Computer.Clipboard.SetText("This is a test string.")


The SetText method can accept a format parameter that contains a type of TextDataFormat. The following code writes the string "This is a test string" to the Clipboard
as RTF text.

VB

My.Computer.Clipboard.SetText("This is a test string.",


System.Windows.Forms.TextDataFormat.Rtf)

Use the SetData method to write data to the Clipboard. This example writes the DataObject dataChunk to the Clipboard in the custom format specialFormat.

VB

My.Computer.Clipboard.SetData("specialFormat", dataChunk)

Use the SetAudio method to write audio data to the Clipboard. This example creates the byte array musicReader, reads the file cool.wav into it, and then writes it to the
Clipboard.

VB

Dim musicReader = My.Computer.FileSystem.ReadAllBytes("cool.wav")


My.Computer.Clipboard.SetAudio(musicReader)

Security Note

Because the Clipboard can be accessed by other users, do not use it to store sensitive information, such as passwords or confidential data.

See Also
Tasks
How to: Read Object Data from an XML File (C# and Visual Basic)
How to: Write Object Data to an XML File (C# and Visual Basic)
Reference
ClipboardProxy
GetAudioStream
SetDataObject

2014 Microsoft. All rights reserved.


Getting Information about the Computer (Visual Basic)
Visual Studio 2012

The My.Computer.Info object provides properties for getting information about the computer's memory, loaded assemblies, name, and operating system.

Remarks
This table lists tasks commonly accomplished through the My.Computer.Info object and points to topics demonstrating how to perform each.

To See

Determine how much virtual address space is available for the computer on which the application is installed TotalVirtualMemory

Determine the platform type of the computer on which the application is running OSPlatform

Determine the operating system of the computer on which the application is running OSFullName

Determine what service packs have been installed on the computer on which the application is running OSVersion

Determine the installed UICulture on the computer on which the application is running. InstalledUICulture

See Also
Reference
Info

2014 Microsoft. All rights reserved.


Accessing the Keyboard (Visual Basic)
Visual Studio 2012

The My.Computer.Keyboard object provides properties for accessing the current state of the keyboard, such as what keys are currently pressed, and provides a method
to send keystrokes to the active window.

Tasks
This table lists tasks associated with the My.Computer.Keyboard object and points to topics demonstrating how to perform each task.

To See

Determine whether CAPS LOCK is on CapsLock

Determine whether the SHIFT key is down ShiftKeyDown

Determine whether the ALT key is down AltKeyDown

Determine whether the CTRL key is down CtrlKeyDown

Determine whether NUM LOCK is on NumLock

Determine whether SCROLL LOCK is on ScrollLock

Start an application and send it keystrokes How to: Start an Application and Send it Keystrokes (Visual Basic)

See Also
Reference
Keyboard
Keys

2014 Microsoft. All rights reserved.


How to: Start an Application and Send it Keystrokes (Visual
Basic)
Visual Studio 2012

This example uses the Shell function to start the calculator application and then multiplies two numbers by sending keystrokes using the
My.Computer.Keyboard.SendKeys method.

Example
VB

Dim ProcID As Integer


' Start the Calculator application, and store the process id.
ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)
' Activate the Calculator application.
AppActivate(ProcID)
' Send the keystrokes to the Calculator application.
My.Computer.Keyboard.SendKeys("22", True)
My.Computer.Keyboard.SendKeys("*", True)
My.Computer.Keyboard.SendKeys("44", True)
My.Computer.Keyboard.SendKeys("=", True)
' The result is 22 * 44 = 968.

Robust Programming
A ArgumentException exception is raised if an application with the requested process identifier cannot be found.

Security
The call to the Shell function requires full trust (SecurityException class).

See Also
Reference
SendKeys
Shell
AppActivate

2014 Microsoft. All rights reserved.


Accessing the Mouse (Visual Basic)
Visual Studio 2012

The My.Computer.Mouse object provides a way to find information about the computer's mouse, such as if a mouse exists, the number of mouse buttons, and details
about the mouse wheel.

Remarks
This table lists tasks associated with the My.Computer.Mouse object and points to topics demonstrating how to accomplish each.

To See

Determine whether the mouse has a scroll wheel. WheelExists

Determine whether the left and right mouse buttons have been swapped ButtonsSwapped

Set how much to scroll when the mouse wheel is rotated one notch. WheelScrollLines

See Also
Reference
Mouse

2014 Microsoft. All rights reserved.


Performing Network Operations (Visual Basic)
Visual Studio 2012

The following tables list tasks associated with the My.Computer.Network object.

In This Section
How to: Upload a File in Visual Basic
Demonstrates how to upload a file and store it to a remote location using My.Computer.Network.

How to: Download a File in Visual Basic


Demonstrates how to download a file from a remote location using My.Computer.Network.

How to: Check Connection Status in Visual Basic


Shows how to determine whether the computer has a working network connection.

Reference
Network
Lists methods, properties, and events for working with the network.

DownloadFile
Describes the DownloadFile method.

Ping
Describes the Ping method.

UploadFile
Describes the UploadFile method.

IsAvailable
Describes the IsAvailable property.

2014 Microsoft. All rights reserved.


How to: Upload a File in Visual Basic
Visual Studio 2012

The UploadFile method can be used to upload a file and store it to a remote location. If the ShowUI parameter is set to True, a dialog box is displayed that shows the
progress of the download and allows users to cancel the operation.

To upload a file

Use the UploadFile method to upload a file, specifying the source file's location and the target directory location as a string or URI (Uniform Resource
Identifier).This example uploads the file Order.txt to http://www.cohowinery.com/uploads.aspx.

VB

My.Computer.Network.UploadFile(
"C:\My Documents\Order.txt",
"http://www.cohowinery.com/upload.aspx")

To upload a file and show the progress of the operation

Use the UploadFile method to upload a file, specifying the source file's location and the target directory location as a string or URI. This example uploads the file
Order.txt to http://www.cohowinery.com/uploads.aspx without supplying a user name or password, shows the progress of the upload, and has a time-out
interval of 500 milliseconds.

VB

My.Computer.Network.UploadFile(
"C:\My Documents\Order.txt",
"http://www.cohowinery.com/upload.aspx", "", "", True, 500)

To upload a file, supplying a user name and password

Use the UploadFile method to upload a file, specifying the source file's location and the target directory location as a string or URI, and specifying the user name
and the password. This example uploads the file Order.txt to http://www.cohowinery.com/uploads.aspx, supplying the user name anonymous and a blank
password.

VB

My.Computer.Network.UploadFile(
"C:\My Documents\Order.txt",
"http://www.cohowinery.com/upload.aspx", "anonymous", "")

Robust Programming
The following conditions may throw an exception:

The local file path is not valid (ArgumentException).

Authentication failed (SecurityException).

The connection timed out (TimeoutException).

See Also
Tasks
How to: Download a File in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
Network
UploadFile

2014 Microsoft. All rights reserved.


How to: Download a File in Visual Basic
Visual Studio 2012

The DownloadFile method can be used to download a remote file and store it to a specific location. If the ShowUI parameter is set to True, a dialog box is displayed
showing the progress of the download and allowing users to cancel the operation. By default, existing files having the same name are not overwritten; if you want to
overwrite existing files, set the overwrite parameter to True.

The following conditions may cause an exception:

Drive name is not valid (ArgumentException).

Necessary authentication has not been supplied (UnauthorizedAccessException or SecurityException).

The server does not respond within the specified connectionTimeout (TimeoutException).

The request is denied by the Web site (WebException).

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that
you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Security Note

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file. Verify all inputs
before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

To download a file

Use the DownloadFile method to download the file, specifying the target file's location as a string or URI and specifying the location at which to store the file. This
example downloads the file WineList.txt from http://www.cohowinery.com/downloads and saves it to C:\Documents and Settings\All Users\Documents:

VB

My.Computer.Network.DownloadFile(
"http://www.cohowinery.com/downloads/WineList.txt",
"C:\Documents and Settings\All Users\Documents\WineList.txt")

To download a file, specifying a time-out interval

Use the DownloadFile method to download the file, specifying the target file's location as a string or URI, specifying the location at which to store the file, and
specifying the time-out interval in milliseconds (the default is 1000). This example downloads the file WineList.txt from http://www.cohowinery.com/downloads
and saves it to C:\Documents and Settings\All Users\Documents, specifying a time-out interval of 500 milliseconds:

VB

My.Computer.Network.DownloadFile(
"http://www.cohowinery.com/downloads/WineList.txt",
"C:\Documents and Settings\All Users\Documents\WineList.txt", False, 500)

To download a file, supplying a user name and password

Use the DownLoadFile method to download the file, specifying the target file's location as a string or URI and specifying the location at which to store the file, the
user name, and the password. This example downloads the file WineList.txt from http://www.cohowinery.com/downloads and saves it to C:\Documents and
Settings\All Users\Documents, with the user name anonymous and a blank password.

VB

My.Computer.Network.DownloadFile(
"http://www.cohowinery.com/downloads/WineList.txt",
"C:\Documents and Settings\All Users\Documents\WineList.txt", "anonymous", "")

Security Note

The FTP protocol used by the DownLoadFile method sends information, including passwords, in plain text and should not be used for transmitting sensitive
information.

See Also
Tasks
How to: Upload a File in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
Network
DownloadFile

2014 Microsoft. All rights reserved.


How to: Check Connection Status in Visual Basic
Visual Studio 2012

The IsAvailable property can be used to determine whether the computer has a working network or Internet connection.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that
you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To check whether a computer has a working connection

Determine whether the IsAvailable property is True or False. The following code checks the property's status and reports it:

VB

If My.Computer.Network.IsAvailable Then
MsgBox("Computer is connected.")
Else
MsgBox("Computer is not connected.")
End If

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and Networking. For more information,
see Code Snippets.

See Also
Reference
Network
IsAvailable

2014 Microsoft. All rights reserved.


Accessing the Computer's Ports (Visual Basic)
Visual Studio 2012

The My.Computer.Ports object provides a property and a method for accessing the computer's serial ports.

In This Section
How to: Show Available Serial Ports in Visual Basic
Demonstrates how to show available serial ports.

How to: Dial Modems Attached to Serial Ports in Visual Basic


Demonstrates how to dial a modem attached to the serial port of a computer.

How to: Send Strings to Serial Ports in Visual Basic


Demonstrates how to send a string to a computer's serial port.

How to: Receive Strings From Serial Ports in Visual Basic


Demonstrates how to receive a string from a computer's serial port.

Port Operations in the .NET Framework with Visual Basic


Describes how to use the .NET Framework when performing port operations.

Reference
Ports
Describes the My.Computer.Ports object and its members.

SerialPortNames
Describes the SerialPortNames property, which gets a collection of the names of the serial ports on the computer.

OpenSerialPort
Describes the OpenSerialPort method, which creates and opens a SerialPort object.

Related Sections
SerialPort
Describes the .NET Framework SerialPort class.

2014 Microsoft. All rights reserved.


How to: Show Available Serial Ports in Visual Basic
Visual Studio 2012

This topic describes how to use My.Computer.Ports to show the available serial ports of the computer in Visual Basic.

To allow a user to select which port to use, the names of the serial ports are placed in a ListBox control.

Example
This example loops over all the strings that the My.Computer.Ports.SerialPortNames property returns. These strings are the names of the available serial ports on the
computer.

Typically, a user selects which serial port the application should use from the list of available ports. In this example, the serial port names are stored in a ListBox control.
For more information, see ListBox Control (Windows Forms).

VB

Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
ListBox1.Items.Add(sp)
Next
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and Networking. For more information, see
Code Snippets.

Compiling the Code


This example requires:

A project reference to System.Windows.Forms.dll.

Access to the members of the System.Windows.Forms namespace. Add an Imports statement if you are not fully qualifying member names in your code. For
more information, see Imports Statement (.NET Namespace and Type).

That your form have a ListBox control named ListBox1.

Robust Programming
You do not have to use the ListBox control to display the available serial port names. Instead, you can use a ComboBox or other control. If the application does not need
a response from the user, you can use a TextBox control to display the information.

Note

The port names returned by My.Computer.Ports.SerialPortNames may be incorrect when run on Windows 98. To prevent application errors, use exception
handling, such as the Try...Catch...Finally statement or the Using statement, when using the port names to open ports.

See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
Reference
Ports

2014 Microsoft. All rights reserved.


How to: Dial Modems Attached to Serial Ports in Visual Basic
Visual Studio 2012

This topic describes how to use My.Computer.Ports to dial a modem in Visual Basic.

Typically, the modem is connected to one of the serial ports on the computer. For your application to communicate with the modem, it must send commands to the
appropriate serial port.

To dial a modem

1. Determine which serial port the modem is connected to. This example assumes the modem is on COM1.

2. Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see OpenSerialPort.

The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the serial port should appear within this
block, or within a Try...Catch...Finally block.

VB

Using com1 As IO.Ports.SerialPort =


My.Computer.Ports.OpenSerialPort("COM1", 9600)
End Using

3. Set the DtrEnable property to indicate that the computer is ready to accept an incoming transmission from the modem.

VB

com1.DtrEnable = True

4. Send the dial command and the phone number to the modem through the serial port by means of the Write method.

VB

com1.Write("ATDT 555-0100" & vbCrLf)

Example
VB

Sub DialModem()
' Dial a number via an attached modem on COM1.
Using com1 As IO.Ports.SerialPort =
My.Computer.Ports.OpenSerialPort("COM1", 9600)
com1.DtrEnable = True
com1.Write("ATDT 555-0100" & vbCrLf)
' Insert code to transfer data to and from the modem.
End Using
End Sub

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and Networking. For more information, see
Code Snippets.

Compiling the Code


This example requires a reference to the System namespace.

Robust Programming
This example assumes the modem is connected to COM1. We recommend that your code allow the user to select the desired serial port from a list of available ports.
For more information, see How to: Show Available Serial Ports in Visual Basic.

This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more information, see Using Statement (Visual
Basic).

In this example, the application disconnects the serial port after it dials the modem. Realistically, you will want to transfer data to and from the modem. For more
information, see How to: Receive Strings From Serial Ports in Visual Basic.

See Also
Tasks
How to: Send Strings to Serial Ports in Visual Basic
How to: Receive Strings From Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
Ports
SerialPort

2014 Microsoft. All rights reserved.


How to: Send Strings to Serial Ports in Visual Basic
Visual Studio 2012

This topic describes how to use My.Computer.Ports to send strings to the computer's serial ports in Visual Basic.

Example
This example sends a string to the COM1 serial port. You may need to use a different serial port on your computer.

Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see OpenSerialPort.

The Using block allows the application to close the serial port even if it generates an exception. All code that manipulates the serial port should appear within this block
or within a Try...Catch...Finally block.

The WriteLine method sends the data to the serial port.

VB

Sub SendSerialData(ByVal data As String)


' Send strings to a serial port.
Using com1 As IO.Ports.SerialPort =
My.Computer.Ports.OpenSerialPort("COM1")
com1.WriteLine(data)
End Using
End Sub

Compiling the Code


This example assumes the computer is using COM1.

Robust Programming
This example assumes the computer is using COM1; for more flexibility, the code should allow the user to select the desired serial port from a list of available ports. For
more information, see How to: Show Available Serial Ports in Visual Basic.

This example uses a Using block to make sure that the application closes the port even if it throws an exception. For more information, see Using Statement (Visual
Basic).

See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
Ports
SerialPort

2014 Microsoft. All rights reserved.


How to: Receive Strings From Serial Ports in Visual Basic
Visual Studio 2012

This topic describes how to use My.Computer.Ports to receive strings from the computer's serial ports in Visual Basic.

To receive strings from the serial port

1. Initialize the return string.

VB

Dim returnStr As String = ""

2. Determine which serial port should provide the strings. This example assumes it is COM1.

3. Use the My.Computer.Ports.OpenSerialPort method to obtain a reference to the port. For more information, see OpenSerialPort.

The Try...Catch...Finally block allows the application to close the serial port even if it generates an exception. All code that manipulates the serial port should
appear within this block.

VB

Dim com1 As IO.Ports.SerialPort = Nothing


Try
com1 = My.Computer.Ports.OpenSerialPort("COM1")
com1.ReadTimeout = 10000

Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com1 IsNot Nothing Then com1.Close()
End Try

4. Create a Do loop for reading lines of text until no more lines are available.

VB

Do
Loop

5. Use the ReadLine method to read the next available line of text from the serial port.

VB

Dim Incoming As String = com1.ReadLine()

6. Use an If statement to determine if the ReadLine method returns Nothing (which means no more text is available). If it does return Nothing, exit the Do loop.

VB

If Incoming Is Nothing Then


Exit Do
End If

7. Add an Else block to the If statement to handle the case if the string is actually read. The block appends the string from the serial port to the return string.

VB

Else
returnStr &= Incoming & vbCrLf

8. Return the string.

VB

Return returnStr

Example
VB

Function ReceiveSerialData() As String


' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com1 As IO.Ports.SerialPort = Nothing
Try
com1 = My.Computer.Ports.OpenSerialPort("COM1")
com1.ReadTimeout = 10000
Do
Dim Incoming As String = com1.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com1 IsNot Nothing Then com1.Close()
End Try

Return returnStr
End Function

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Connectivity and Networking. For more information, see
Code Snippets.

Compiling the Code


This example assumes the computer is using COM1.

Robust Programming
This example assumes the computer is using COM1. For more flexibility, the code should allow the user to select the desired serial port from a list of available ports. For
more information, see How to: Show Available Serial Ports in Visual Basic.

This example uses a Try...Catch...Finally block to make sure that the application closes the port and to catch any timeout exceptions. For more information, see
Try...Catch...Finally Statement (Visual Basic).

See Also
Tasks
How to: Dial Modems Attached to Serial Ports in Visual Basic
How to: Send Strings to Serial Ports in Visual Basic
How to: Show Available Serial Ports in Visual Basic
Reference
Ports
SerialPort

2014 Microsoft. All rights reserved.


Port Operations in the .NET Framework with Visual Basic
Visual Studio 2012

You can access your computer's serial ports through the .NET Framework classes in the System.IO.Ports namespace. The most important class, SerialPort, provides a
framework for synchronous and event-driven I/O, access to pin and break states, and access to serial driver properties. It can be wrapped in a Stream object, accessible
through the BaseStream property. Wrapping SerialPort in a Stream object allows the serial port to be accessed by classes that use streams. The namespace includes
enumerations that simplify the control of serial ports.

The simplest way to create a SerialPort object is through the OpenSerialPort method.

Note

You cannot use .NET Framework classes to directly access other types of ports, such as parallel ports, USB ports, and so on.

Enumerations
This table lists and describes the main enumerations used for accessing a serial port:

Enumeration Description

Handshake Specifies the control protocol used in establishing a serial port communication for a SerialPort object.

Parity Specifies the parity bit for a SerialPort object.

SerialData Specifies the type of character that was received on the serial port of the SerialPort object.

SerialError Specifies errors that occur on the SerialPort object

SerialPinChange Specifies the type of change that occurred on the SerialPort object.

StopBits Specifies the number of stop bits used on the SerialPort object.

See Also
Reference
Ports
Other Resources
Accessing the Computer's Ports (Visual Basic)

2014 Microsoft. All rights reserved.


Reading from and Writing to the Registry (Visual Basic)
Visual Studio 2012

This topic describes task and conceptual topics that are associated with the registry.

When programming in Visual Basic, you can choose to access the registry by means of either the functions provided by Visual Basic or the registry classes of the .NET
Framework. The registry hosts information from the operating system as well as information from applications hosted on the machine. Working with the registry may
compromise security by allowing inappropriate access to system resources or protected information.

In This Section
How to: Create a Registry Key and Set Its Value in Visual Basic
Describes how to use the CreateSubKey and SetValue methods of the My.Computer.Registry object to create a registry key and set its value.

How to: Read a Value from a Registry Key in Visual Basic


Describes how to use the GetValue method of the My.Computer.Registry object to read a value from a registry key.

How to: Delete a Registry Key in Visual Basic


Describes how to use the DeleteSubKey method of the My.Computer.Registry.CurrentUser property to delete a registry key.

Reading from and Writing to the Registry Using the Microsoft.Win32 Namespace (Visual Basic)
Describes how to use the Registry and RegistryKey classes of the .NET Framework to access the registry.

Security and the Registry (Visual Basic)


Discusses security issues involving the registry.

Related Sections
RegistryProxy
Lists and explains members of the My.Computer.Registry object.

Registry
Presents an overview of the Registry class, along with links to individual keys and members.

2014 Microsoft. All rights reserved.


How to: Create a Registry Key and Set Its Value in Visual Basic
Visual Studio 2012

The CreateSubKey method of the My.Computer.Registry object can be used to create a registry key.

Procedure

To create a registry key

Use the CreateSubKey method, specifying which hive to place the key under as well as the name of the key. The parameter Subkey is not case-sensitive. This
example creates the registry key MyTestKey under HKEY_CURRENT_USER.

VB

My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")

To create a registry key and set a value in it

1. Use the CreateSubkey method, specifying which hive to place the key under as well as the name of the key. This example creates the registry key MyTestKey
under HKEY_CURRENT_USER.

VB

My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")

2. Set the value with the SetValue method. This example sets the string value. "MyTestKeyValue" to "This is a test value".

VB

My.Computer.Registry.SetValue("HKEY_CURRENT_USER\MyTestKey",
"MyTestKeyValue", "This is a test value.")

Example
This example creates the registry key MyTestKey under HKEY_CURRENT_USER and then sets the string value MyTestKeyValue to This is a test value.

VB

My.Computer.Registry.CurrentUser.CreateSubKey("MyTestKey")
' Change MyTestKeyValue to This is a test value.
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\MyTestKey",
"MyTestKeyValue", "This is a test value.")

Robust Programming
Examine the registry structure to find a suitable location for your key. For example, you may want to open the HKEY_CURRENT_USER\Software key of the current user,
and create a key with your company's name. Then add the registry values to your company's key.

When reading the registry from a Web application, the current user depends on the authentication and impersonation implemented in the Web application.

It is more secure to write data to the user folder (CurrentUser) rather than to the local computer (LocalMachine).

When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a malicious one, may have already created the
value and have access to it. When you put data in the registry value, the data is available to the other process. To prevent this, use the GetValue method. It returns
Nothing if the key does not already exist.

It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by ACLs (Access Control Lists).

The following conditions may cause an exception:

The name of the key is Nothing (ArgumentNullException).

The user does not have permissions to create registry keys (SecurityException).

The key name exceeds the 255-character limit (ArgumentException).

The key is closed (IOException).

The registry key is read-only (UnauthorizedAccessException).


Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a partial-trust context, the process might
throw an exception due to insufficient privileges. Similarly, the user must have the correct ACLs for creating or writing to settings. For example, a local application that
has the code access security permission might not have operating system permission. For more information, see Code Access Security Basics.

See Also
Reference
RegistryProxy
CurrentUser
CreateSubKey
Concepts
Code Access Security Basics
Other Resources
Reading from and Writing to the Registry (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read a Value from a Registry Key in Visual Basic
Visual Studio 2012

The GetValue method of the My.Computer.Registry object can be used to read values in the Windows registry.

If the key, "Software\MyApp" in the following example, does not exist, an exception is thrown. If the ValueName, "Name" in the following example, does not exist, Nothing
is returned.

The GetValue method can also be used to determine whether a given value exists in a specific registry key.

When code reads the registry from a Web application, the current user is determined by the authentication and impersonation that is implemented in the Web application.

To read a value from a registry key

Use the GetValue method, specifying the path and name) to read a value from registry key. The following example reads the value Name from
HKEY_CURRENT_USER\Software\MyApp and displays it in a message box.

VB

Dim readValue = My.Computer.Registry.GetValue(


"HKEY_CURRENT_USER\Software\MyApp", "Name", Nothing)
MsgBox("The value is " & readValue)

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Windows Operating System > Registry. For more
information, see Code Snippets.

To determine whether a value exists in a registry key

Use the GetValue method to retrieve the value. The following code checks whether the value exists and returns a message if it does not.

VB

If My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\TestApp",
"TestValue", Nothing) Is Nothing Then
MsgBox("Value does not exist.")
End If

Robust Programming
The registry holds top-level, or root, keys that are used to store data. For instance, the HKEY_LOCAL_MACHINE root key is used for storing machine-level settings used
by all users, while HKEY_CURRENT_USER is used for storing data specific to an individual user.

The following conditions may cause an exception:

The name of the key is Nothing (ArgumentNullException).

The user does not have permissions to read from registry keys (SecurityException).

The key name exceeds the 255-character limit (ArgumentException).

Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a partial-trust context, the process might
throw an exception due to insufficient privileges. Similarly, the user must have the correct ACLs for creating or writing to settings. For example, a local application that
has the code access security permission might not have operating system permission. For more information, see Code Access Security Basics.

See Also
Reference
RegistryProxy
RegistryHive
Other Resources
Reading from and Writing to the Registry (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Delete a Registry Key in Visual Basic
Visual Studio 2012

The DeleteSubKey(String) and DeleteSubKey(String, Boolean) methods can be used to delete registry keys.

Procedure

To delete a registry key

Use the DeleteSubKey method to delete a registry key. This example deletes the key Software/TestApp in the CurrentUser hive. You can change this in the code
to the appropriate string, or have it rely on user-supplied information.

VB

My.Computer.Registry.CurrentUser.DeleteSubKey(
"Software\TestApp")

Robust Programming
The DeleteSubKey method returns an empty string if the key/value pair does not exist.

The following conditions may cause an exception:

The name of the key is Nothing (ArgumentNullException).

The user does not have permissions to delete registry keys (SecurityException).

The key name exceeds the 255-character limit (ArgumentException).

The registry key is read-only (UnauthorizedAccessException).

Security
Registry calls fail if either sufficient run-time permissions are not granted (RegistryPermission) or if the user does not have the correct access (as determined by the
ACLs) for creating or writing to settings. For example, a local application that has the code access security permission might not have operating system permission.

See Also
Reference
DeleteSubKey
DeleteSubKey
RegistryKey
Concepts
Security and the Registry (Visual Basic)
Other Resources
Reading from and Writing to the Registry (Visual Basic)

2014 Microsoft. All rights reserved.


Reading from and Writing to the Registry Using the
Microsoft.Win32 Namespace (Visual Basic)
Visual Studio 2012

Although My.Computer.Registry should cover your basic needs when programming against the registry, you can also use the Registry and RegistryKey classes in the
Microsoft.Win32 namespace of the .NET Framework.

Keys in the Registry Class


The Registry class supplies the base registry keys that can be used to access subkeys and their values. The base keys themselves are read-only. The following table lists
and describes the seven keys exposed by the Registry class.

Key Description

ClassesRoot Defines the types of documents and the properties associated with those types.

CurrentConfig Contains hardware configuration information that is not user-specific.

CurrentUser Contains information about the current user preferences, such as environmental variables.

DynData Contains dynamic registry data, such as that used by Virtual Device Drivers.

LocalMachine Contains five subkeys (Hardware, SAM, Security, Software, and System) that hold the configuration data for the local computer.

PerformanceData Contains performance information for software components.

Users Contains information about the default user preferences.

Security Note

It is more secure to write data to the current user (CurrentUser) than to the local computer (LocalMachine). A condition that's typically referred to as "squatting"
occurs when the key you are creating was previously created by another, possibly malicious, process. To prevent this from occurring, use a method, such as GetValue,
that returns Nothing if the key does not already exist.

Reading a Value from the Registry


The following code shows how to read a string from HKEY_CURRENT_USER.

VB

Dim regVersion As Microsoft.Win32.RegistryKey


Dim keyValue = "Software\\Microsoft\\TestApp\\1.0"
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyValue, False)
Dim intVersion As Integer = 0
If regVersion IsNot Nothing Then
intVersion = regVersion.GetValue("Version", 0)
regVersion.Close()
End If

The following code reads, increments, and then writes a string to HKEY_CURRENT_USER.

VB

Dim regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(


"SOFTWARE\\Microsoft\\TestApp\\1.0", True)
If regVersion Is Nothing Then
' Key doesn't exist; create it.
regVersion = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(
"SOFTWARE\\Microsoft\\TestApp\\1.0")
End If

Dim intVersion As Integer = 0


If regVersion IsNot Nothing Then
intVersion = regVersion.GetValue("Version", 0)
intVersion = intVersion + 1
regVersion.SetValue("Version", intVersion)
regVersion.Close()
End If

See Also
Reference
Try...Catch...Finally Statement (Visual Basic)
SystemException
ApplicationException
RegistryProxy
Concepts
Security and the Registry (Visual Basic)
Other Resources
Reading from and Writing to the Registry (Visual Basic)

2014 Microsoft. All rights reserved.


Security and the Registry (Visual Basic)
Visual Studio 2012

This page discusses the security implications of storing data in the registry.

Permissions
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by ACLs (access control lists).

Working with the registry may compromise security by allowing inappropriate access to system resources or protected information. To use these properties, you must
have read and write permissions from the RegistryPermissionAccess enumeration, which controls access to registry variables. Any code running with full trust (under the
default security policy, this is any code installed on the user's local hard disk) has the necessary permissions to access the registry. For more information, see
RegistryPermission class.

Registry variables should not be stored in memory locations where code without RegistryPermission can access them. Similarly, when granting permissions, grant the
minimum privileges necessary to get the job done.

Registry permission access values are defined by the RegistryPermissionAccess enumeration. The following table details its members.

Value Access to Registry Variables

AllAccess Create, read, and write

Create Create

NoAccess No access

Read Read

Write Write

Checking Values in Registry Keys


When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a malicious one, may have already created the
value and have access to it. When you put data in the registry value, the data is available to the other process. To prevent this, use the GetValue method. It returns
Nothing if the key does not already exist.

Security Note

When reading the registry from a Web application, the identity of current user depends on the authentication and impersonation implemented in the Web
application.

See Also
Reference
RegistryProxy
Other Resources
Reading from and Writing to the Registry (Visual Basic)

2014 Microsoft. All rights reserved.


Logging Information from the Application (Visual Basic)
Visual Studio 2012

This section contains topics that cover how to log information from your application using the My.Application.Log or My.Log object, and how to extend the application's
logging capabilities.

The Log object provides methods for writing information to the application's log listeners, and the Log object's advanced TraceSource property provides detailed
configuration information. The Log object is configured by the application's configuration file.

The My.Log object is available only for ASP.NET applications. For client applications, use My.Application.Log. For more information, see Log.

Tasks

To See

Write event information to the application's logs. How to: Write Log Messages (Visual Basic)

Write exception information to the application's logs. How to: Log Exceptions in Visual Basic

Write trace information to the application's logs when the application starts and How to: Log Messages When the Application Starts or Shuts Down (Visual
shuts down. Basic)

Configure My.Application.Log to write information to a text file. How to: Write Event Information to a Text File (Visual Basic)

Configure My.Application.Log to write information to an event log. How to: Write to an Application Event Log (Visual Basic)

Change where My.Application.Log writes information. Walkthrough: Changing Where My.Application.Log Writes Information (Visual
Basic)

Determine where My.Application.Log writes information. Walkthrough: Determining Where My.Application.Log Writes Information
(Visual Basic)

Create a custom log listener for My.Application.Log. Walkthrough: Creating Custom Log Listeners (Visual Basic)

Filter the output of the My.Application.Log logs. Walkthrough: Filtering My.Application.Log Output (Visual Basic)

See Also
Tasks
Troubleshooting: Log Listeners (Visual Basic)
Reference
Log
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


How to: Write Log Messages (Visual Basic)
Visual Studio 2012

You can use the My.Application.Log and My.Log objects to log information about your application. This example shows how to use the My.Application.Log.WriteEntry
method to log tracing information.

For logging exception information, use the My.Application.Log.WriteException method; see How to: Log Exceptions in Visual Basic.

Example
This example uses the My.Application.Log.WriteEntry method to write out the trace information.

VB

Public Sub TracingTest(ByVal fileName As String)


My.Application.Log.WriteEntry(
"Entering TracingTest with argument " &
fileName & ".")
' Code to trace goes here.
My.Application.Log.WriteEntry(
"Exiting TracingTest with argument " &
fileName & ".")
End Sub

Security
Make sure the data you write to the log does not include sensitive information such as user passwords. For more information, see Working with Application Logs in
Visual Basic.

See Also
Tasks
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic)
Walkthrough: Changing Where My.Application.Log Writes Information (Visual Basic)
Walkthrough: Filtering My.Application.Log Output (Visual Basic)
Reference
Log
WriteEntry
WriteException
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


How to: Log Exceptions in Visual Basic
Visual Studio 2012

You can use the My.Application.Log and My.Log objects to log information about exceptions that occur in your application. These examples show how to use the
My.Application.Log.WriteException method to log exceptions that you catch explicitly and exceptions that are unhandled.

For logging tracing information, use the My.Application.Log.WriteEntry method. For more information, see WriteEntry

To log a handled exception

1. Create the method that will generate the exception information.

VB

Public Sub ExceptionLogTest(ByVal fileName As String)


End Sub

2. Use a Try...Catch block to catch the exception.

VB

Try
Catch ex As Exception
End Try

3. Put the code that could generate an exception in the Try block.

Uncomment the Dim and MsgBox lines to cause a NullReferenceException exception.

VB

' Code that might generate an exception goes here.


' For example:
' Dim x As Object
' MsgBox(x.ToString)

4. In the Catch block, use the My.Application.Log.WriteException method to write the exception information.

VB

My.Application.Log.WriteException(ex,
TraceEventType.Error,
"Exception in ExceptionLogTest " &
"with argument " & fileName & ".")

The following example shows the complete code for logging a handled exception.

VB

Public Sub ExceptionLogTest(ByVal fileName As String)


Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex,
TraceEventType.Error,
"Exception in ExceptionLogTest " &
"with argument " & fileName & ".")
End Try
End Sub

To log an unhandled exception

1. Have a project selected in Solution Explorer. On the Project menu, choose Properties.

2. Click the Application tab.

3. Click the View Application Events button to open the Code Editor.

This opens the ApplicationEvents.vb file.

4. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.

5. On the Declarations menu, choose UnhandledException.

The application raises the UnhandledException event before the main application runs.
6. Add the My.Application.Log.WriteException method to the UnhandledException event handler.

VB

My.Application.Log.WriteException(e.Exception,
TraceEventType.Critical,
"Application shut down at " &
My.Computer.Clock.GmtTime.ToString)

The following example shows the complete code for logging an unhandled exception.

VB

Private Sub MyApplication_UnhandledException(


ByVal sender As Object,
ByVal e As ApplicationServices.UnhandledExceptionEventArgs
) Handles Me.UnhandledException
My.Application.Log.WriteException(e.Exception,
TraceEventType.Critical,
"Application shut down at " &
My.Computer.Clock.GmtTime.ToString)
End Sub

See Also
Tasks
How to: Write Log Messages (Visual Basic)
Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic)
Walkthrough: Changing Where My.Application.Log Writes Information (Visual Basic)
Reference
Log
WriteEntry
WriteException
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


How to: Log Messages When the Application Starts or Shuts
Down (Visual Basic)
Visual Studio 2012

You can use the My.Application.Log and My.Log objects to log information about events that occur in your application. This example shows how to use the
My.Application.Log.WriteEntry method with the Startup and Shutdown events to write tracing information.

To access the application's event-handler code

1. Have a project selected in Solution Explorer. On the Project menu, choose Properties.

2. Click the Application tab.

3. Click the View Application Events button to open the Code Editor.

This opens the ApplicationEvents.vb file.

To log messages when the application starts

1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.

2. On the Declarations menu, choose Startup.

The application raises the Startup event before the main application runs.

3. Add the My.Application.Log.WriteEntry method to the Startup event handler.

VB

My.Application.Log.WriteEntry("Application started at " &


My.Computer.Clock.GmtTime.ToString)

To log messages when the application shuts down

1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.

2. On the Declarations menu, choose Shutdown.

The application raises the Shutdown event after the main application runs, but before it shuts down.

3. Add the My.Application.Log.WriteEntry method to the Shutdown event handler.

VB

My.Application.Log.WriteEntry("Application shut down at " &


My.Computer.Clock.GmtTime.ToString)

Example
You can use the Project Designer to access the application events in the Code Editor. For more information, see Application Page, Project Designer (Visual Basic).

VB

Private Sub MyApplication_Startup(


ByVal sender As Object,
ByVal e As ApplicationServices.StartupEventArgs
) Handles Me.Startup
My.Application.Log.WriteEntry("Application started at " &
My.Computer.Clock.GmtTime.ToString)
End Sub

Private Sub MyApplication_Shutdown(


ByVal sender As Object,
ByVal e As System.EventArgs
) Handles Me.Shutdown
My.Application.Log.WriteEntry("Application shut down at " &
My.Computer.Clock.GmtTime.ToString)
End Sub

See Also
Reference
Application Page, Project Designer (Visual Basic)
Microsoft.VisualBasic.Logging.Log
WriteEntry
WriteException
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


How to: Write to an Application Event Log (Visual Basic)
Visual Studio 2012

You can use the My.Application.Log and My.Log objects to write information about events that occur in your application. This example shows how to configure an event
log listener so My.Application.Log writes tracing information to the Application event log.

You cannot write to the Security log. In order to write to the System log, you must be a member of the LocalSystem or Administrator account.

To view an event log, you can use Server Explorer or Windows Event Viewer. For more information, see ETW Events in the .NET Framework.

Note

Event logs are not supported on Windows 95, Windows 98, or Windows Millennium Edition.

To add and configure the event log listener

1. Right-click app.config in Solution Explorer and choose Open.

- or -

If there is no app.config file,

a. On the Project menu, choose Add New Item.

b. From the Add New Item dialog box, choose Application Configuration File.

c. Click Add.

2. Locate the <listeners> section in the application configuration file.

You will find the <listeners> section in the <source> section with the name attribute "DefaultSource", which is nested under the <system.diagnostics> section,
which is nested under the top-level <configuration> section.

3. Add this element to that <listeners> section:

<add name="EventLog"/>

4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.

5. Add this element to that <sharedListeners> section:

<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="APPLICATION_NAME"/>

Replace APPLICATION_NAME with the name of your application.

Note

Typically, an application writes only errors to the event log. For information on filtering log output, see Walkthrough: Filtering My.Application.Log Output (Visual
Basic).

To write event information to the event log

Use the My.Application.Log.WriteEntry or My.Application.Log.WriteException method to write information to the event log. For more information, see How to:
Write Log Messages (Visual Basic) and How to: Log Exceptions in Visual Basic.

After you configure the event log listener for an assembly, it receives all messages that My.Applcation.Log writes from that assembly.

See Also
Tasks
How to: Log Exceptions in Visual Basic
Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic)
Reference
Log
WriteEntry
WriteException
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


How to: Write Event Information to a Text File (Visual Basic)
Visual Studio 2012

You can use the My.Application.Log and My.Log objects to log information about events that occur in your application. This example shows how to use the
My.Application.Log.WriteEntry method to log tracing information to a log file.

To add and configure the file log listener

1. Right-click app.config in Solution Explorer and choose Open.

- or -

If there is no app.config file:

a. On the Project menu, choose Add New Item.

b. From the Add New Item dialog box, choose Application Configuration File.

c. Click Add.

2. Locate the <listeners> section in the application configuration file.

You will find the <listeners> section in the <source> section with the name attribute "DefaultSource", which is nested under the <system.diagnostics> section, which
is nested under the top-level <configuration> section.

3. Add this element to that <listeners> section:

<add name="FileLogListener" />

4. Locate the <sharedListeners> section in the <system.diagnostics> section, nested under the top-level <configuration> section.

5. Add this element to that <sharedListeners> section:

<add name="FileLogListener"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogListenerWriter"
location="Custom"
customlocation="c:\temp\" />

Change the value of the customlocation attribute to the log directory.

Note

To set the value of a listener property, use an attribute that has the same name as the property, with all letters in the name lowercase. For example, the location
and customlocation attributes set the values of the Location and CustomLocation properties.

To write event information to the file log

Use the My.Application.Log.WriteEntry or My.Application.Log.WriteException method to write information to the file log. For more information, see How to:
Write Log Messages (Visual Basic) and How to: Log Exceptions in Visual Basic.

After you configure the file log listener for an assembly, it receives all messages that My.Application.Log writes from that assembly.

See Also
Tasks
How to: Log Exceptions in Visual Basic
Reference
Log
WriteEntry
WriteException
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


Working with Application Logs in Visual Basic
Visual Studio 2012

The My.Applicaton.Log and My.Log objects make it easy to write logging and tracing information to logs.

How Messages are Logged


First, the severity of the message is checked with the Switch property of the log's TraceSource property. By default, only messages of severity "Information" and higher
are passed on to the trace listeners, specified in the log's TraceListener collection. Then, each listener compares the severity of the message to the listener's Switch
property. If the message's severity is high enough, the listener writes out the message.

The following diagram shows how a message written to the WriteEntry method gets passed to the WriteLine methods of the log's trace listeners:

You can change the behavior of the log and the trace listeners by changing the application's configuration file. The following diagram shows the correspondence
between the parts of the log and the configuration file.

Where Messages are Logged


If the assembly has no configuration file, the My.Application.Log and My.Log objects write to the application's debug output (through the DefaultTraceListener class).
In addition, the My.Application.Log object writes to the assembly's log file (through the FileLogTraceListener class), while the My.Log object writes to the ASP.NET Web
page's output (through the WebPageTraceListener class).

The debug output can be viewed in the Visual Studio Output window when running your application in debug mode. To open the Output window, click the Debug menu
item, point to Windows, and then click Output. In the Output window, select Debug from the Show output from box.

By default, My.Application.Log writes the log file in the path for the user's application data. You can get the path from the FullLogFileName property of the
DefaultFileLogWriter object. The format of that path is as follows:

BasePath\CompanyName\ProductName\ProductVersion

A typical value for BasePath is as follows.

C:\Documents and Settings\username\Application Data

The values of CompanyName, ProductName, and ProductVersion come from the application's assembly information. The form of the log file name is AssemblyName.log,
where AssemblyName is the file name of the assembly without the extension. If more than one log file is needed, such as when the original log is unavailable when the
application attempts to write to the log, the form for the log file name is AssemblyName-iteration.log, where iteration is a positive Integer.

You can override the default behavior by adding or changing the computer's and the application's configuration files. For more information, see Walkthrough: Changing
Where My.Application.Log Writes Information (Visual Basic).
Configuring Log Settings
The Log object has a default implementation that works without an application configuration file, app.config. To change the defaults, you must add a configuration file
with the new settings. For more information, see Walkthrough: Filtering My.Application.Log Output (Visual Basic).

The log configuration sections are located in the <system.diagnostics> node in the main <configuration> node of the app.config file. Log information is defined in
several nodes:

The listeners for the Log object are defined in the <sources> node named DefaultSource.

The severity filter for the Log object is defined in the <switches> node named DefaultSwitch.

The log listeners are defined in the <sharedListeners> node.

Examples of <sources>, <switches>, and <sharedListeners> nodes are shown in the following code:

<configuration>
<system.diagnostics>
<sources>
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"
/>
</sharedListeners>
</system.diagnostics>
</configuration>

Changing Log Settings after Deployment


When you develop an application, its configuration settings are stored in the app.config file, as shown in the examples above. After you deploy your application, you can
still configure the log by editing the configuration file. In a Windows-based application, this file's name is applicationName.exe.config, and it must reside in the same
folder as the executable file. For a Web application, this is the Web.config file associated with the project.

When your application executes the code that creates an instance of a class for the first time, it checks the configuration file for information about the object. For the Log
object, this happens the first time the Log object is accessed. The system examines the configuration file only once for any particular objectthe first time your
application creates the object. Therefore, you may need to restart the application for the changes to take effect.

In a deployed application, you enable trace code by reconfiguring switch objects before your application starts. Typically, this involves turning the switch objects on and
off or by changing the tracing levels, and then restarting your application.

Security Considerations
Consider the following when writing data to the log:

Avoid leaking user information. Ensure that your application writes only approved information to the log. For example, it may be acceptable for the application
log to contain user names, but not user passwords.

Make log locations secure. Any log that contains potentially sensitive information should be stored in a secure location.

Avoid misleading information. In general, your application should validate all data entered by a user before using that data. This includes writing data to the
application log.

Avoid denial of service. If your application writes too much information to the log, it could fill the log or make finding important information difficult.

See Also
Reference
Log
Concepts
Logging Information from the Application (Visual Basic)
2014 Microsoft. All rights reserved.
Walkthrough: Determining Where My.Application.Log Writes
Information (Visual Basic)
Visual Studio 2012

The My.Application.Log object can write information to several log listeners. The log listeners are configured by the computer's configuration file and can be overridden
by an application's configuration file. This topic describes the default settings and how to determine the settings for your application.

For more information about the default output locations, see Working with Application Logs in Visual Basic.

To determine the listeners for My.Application.Log

1. Locate the assembly's configuration file. If you are developing the assembly, you can access the app.config in Visual Studio from the Solution Explorer. Otherwise,
the configuration file name is the assembly's name appended with ".config", and it is located in the same directory as the assembly.

Note

Not every assembly has a configuration file.

The configuration file is an XML file.

2. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", located in the <sources> section. The <sources> section is located
in the <system.diagnostics> section, in the top-level <configuration> section.

If these sections do not exist, then the computer's configuration file may configure the My.Application.Log log listeners. The following steps describe how to
determine what the computer configuration file defines:

a. Locate the computer's machine.config file. Typically, it is located in the SystemRoot\Microsoft.NET\Framework\frameworkVersion\CONFIG directory, where
SystemRoot is the operating system directory, and frameworkVersion is the version of the .NET Framework.

The settings in machine.config can be overridden by an application's configuration file.

If the optional elements listed below do not exist, you can create them.

b. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", in the <sources> section, in the <system.diagnostics>
section, in the top-level <configuration> section.

If these sections do not exist, then the My.Application.Log has only the default log listeners.

3. Locate the <add> elements in the <listeners> section.

These elements add the named log listeners to My.Application.Log source.

4. Locate the <add> elements with the names of the log listeners in the <sharedListeners> section, in the <system.diagnostics> section, in the top-level
<configuration> section.

5. For many types of shared listeners, the listener's initialization data includes a description of where the listener directs the data:

A FileLogTraceListener listener writes to a file log, as described in the introduction.

A EventLogTraceListener listener writes information to the computer event log specified by the initializeData parameter. To view an event log, you can use
Server Explorer or Windows Event Viewer. For more information, see ETW Events in the .NET Framework.

The DelimitedListTraceListener and XmlWriterTraceListener listeners write to the file specified in the initializeData parameter.

A ConsoleTraceListener listener writes to the command-line console.

For information about where other types of log listeners write information, consult that type's documentation.

See Also
Tasks
How to: Log Exceptions in Visual Basic
How to: Write Log Messages (Visual Basic)
Walkthrough: Changing Where My.Application.Log Writes Information (Visual Basic)
Troubleshooting: Log Listeners (Visual Basic)
Reference
Log
DefaultTraceListener
EventLogTraceListener
DelimitedListTraceListener
XmlWriterTraceListener
ConsoleTraceListener
System.Diagnostics
Concepts
Working with Application Logs in Visual Basic
Other Resources
ETW Events in the .NET Framework
2014 Microsoft. All rights reserved.
Walkthrough: Changing Where My.Application.Log Writes
Information (Visual Basic)
Visual Studio 2012

You can use the My.Application.Log and My.Log objects to log information about events that occur in your application. This walkthrough shows how to override the
default settings and cause the Log object to write to other log listeners.

Prerequisites
The Log object can write information to several log listeners. You need to determine the current configuration of the log listeners before changing the configurations.
For more information, see Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic).

You may want to review How to: Write Event Information to a Text File (Visual Basic) or How to: Write to an Application Event Log (Visual Basic).

To add listeners

1. Right-click app.config in Solution Explorer and choose Open.

- or -

If there is no app.config file:

a. On the Project menu, choose Add New Item.

b. From the Add New Item dialog box, select Application Configuration File.

c. Click Add.

2. Locate the <listeners> section, under the <source> section with the name attribute "DefaultSource", in the <sources> section. The <sources> section is in the
<system.diagnostics> section, in the top-level <configuration> section.

3. Add these elements to that <listeners> section.

<!-- Uncomment to connect the application file log. -->


<!-- <add name="FileLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="EventLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="Delimited" /> -->
<!-- Uncomment to connect the XML log. -->
<!-- <add name="XmlWriter" /> -->
<!-- Uncomment to connect the console log. -->
<!-- <add name="Console" /> -->

4. Uncomment the log listeners that you want to receive Log messages.

5. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.

6. Add these elements to that <sharedListeners> section.

<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogWriter" />
<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="sample application"/>
<add name="Delimited"
type="System.Diagnostics.DelimitedListTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleDelimitedFile.txt"
traceOutputOptions="DateTime" />
<add name="XmlWriter"
type="System.Diagnostics.XmlWriterTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleLogFile.xml" />
<add name="Console"
type="System.Diagnostics.ConsoleTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="true" />

7. The content of the app.config file should be similar to the following XML:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.diagnostics>
<sources>
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment to connect the application file log. -->
<!-- <add name="FileLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="EventLog" /> -->
<!-- Uncomment to connect the event log. -->
<!-- <add name="Delimited" /> -->
<!-- Uncomment to connect the XML log. -->
<!-- <add name="XmlWriter" /> -->
<!-- Uncomment to connect the console log. -->
<!-- <add name="Console" /> -->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
initializeData="FileLogWriter" />
<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="sample application"/>
<add name="Delimited"
type="System.Diagnostics.DelimitedListTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleDelimitedFile.txt"
traceOutputOptions="DateTime" />
<add name="XmlWriter"
type="System.Diagnostics.XmlWriterTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="c:\temp\sampleLogFile.xml" />
<add name="Console"
type="System.Diagnostics.ConsoleTraceListener,
System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="true" />
</sharedListeners>
</system.diagnostics>
</configuration>

To reconfigure a listener

1. Locate the listener's <add> element from the <sharedListeners> section.

2. The type attribute gives the name of the listener type. This type must inherit from the TraceListener class. Use the strongly named type name to ensure that the right
type is used. For more information, see the "To reference a strongly named type" section below.

Some types that you can use are:

A FileLogTraceListener listener, which writes to a file log.

A EventLogTraceListener listener, which writes information to the computer event log specified by the initializeData parameter.

The DelimitedListTraceListener and XmlWriterTraceListener listeners, which write to the file specified in the initializeData parameter.

A ConsoleTraceListener listener, which writes to the command-line console.

For information about where other types of log listeners write information, consult that type's documentation.

3. When the application creates the log-listener object, it passes the initializeData attribute as the constructor parameter. The meaning of the initializeData
attribute depends on the trace listener.

4. After creating the log listener, the application sets the listener's properties. These properties are defined by the other attributes in the <add> element. For more
information on the properties for a particular listener, see the documentation for that listener's type.
To reference a strongly named type

1. To ensure that the right type is used for your log listener, make sure to use the fully qualified type name and the strongly named assembly name. The syntax of a
strongly named type is as follows:

<type name>, <assembly name>, <version number>, <culture>, <strong name>

2. This code example shows how to determine the strongly named type name for a fully qualified type"System.Diagnostics.FileLogTraceListener" in this case.

VB

Public Sub DisplayStrongName()


Dim t As Type = GetType(Logging.FileLogTraceListener)
MsgBox(t.FullName & ", " & t.Assembly.FullName)
End Sub

This is the output, and it can be used to uniquely reference a strongly named type, as in the "To add listeners" procedure above.

Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral,


PublicKeyToken=b03f5f7f11d50a3a

See Also
Tasks
How to: Write Event Information to a Text File (Visual Basic)
How to: Write to an Application Event Log (Visual Basic)
Reference
Log
TraceListener
FileLogTraceListener
EventLogTraceListener

2014 Microsoft. All rights reserved.


Walkthrough: Filtering My.Application.Log Output (Visual
Basic)
Visual Studio 2012

This walkthrough demonstrates how to change the default log filtering for the My.Application.Log object, to control what information is passed from the Log object to
the listeners and what information is written by the listeners. You can change the logging behavior even after building the application, because the configuration
information is stored in the application's configuration file.

Getting Started
Each message that My.Application.Log writes has an associated severity level, which filtering mechanisms use to control the log output. This sample application uses
My.Application.Log methods to write several log messages with different severity levels.

To build the sample application

1. Open a new Visual Basic Windows Application project.


2. Add a button named Button1 to Form1.
3. In the Click event handler for Button1, add the following code:
VB

' Activity tracing information


My.Application.Log.WriteEntry("Entering Button1_Click", TraceEventType.Start)

' Tracing information


My.Application.Log.WriteEntry("In Button1_Click", TraceEventType.Information)

' Create an exception to log.


Dim ex As New ApplicationException
' Exception information
My.Application.Log.WriteException(ex)

' Activity tracing information


My.Application.Log.WriteEntry("Leaving Button1_Click", TraceEventType.Stop)

4. Run the application in the debugger.


5. Press Button1.
The application writes the following information to the application's debug output and log file.
DefaultSource Information: 0 : In Button1_Click
DefaultSource Error: 2 : Error in the application.
6. Close the application.

For information on how to view the application's debug output window, see Output Window. For information on the location of the application's log file, see
Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic).

Note

By default, the application flushes the log-file output when the application closes.

In the example above, the second call to the WriteEntry method and the call to the WriteException method produces log output, while the first and last calls to the
WriteEntry method do not. This is because the severity levels of WriteEntry and WriteException are "Information" and "Error", both of which are allowed by the
My.Application.Log object's default log filtering. However, events with "Start" and "Stop" severity levels are prevented from producing log output.

Filtering for All My.Application.Log Listeners


The My.Application.Log object uses a SourceSwitch named DefaultSwitch to control which messages it passes from the WriteEntry and WriteException methods to
the log listeners. You can configure DefaultSwitch in the application's configuration file by setting its value to one of the SourceLevels enumeration values. By default,
its value is "Information".

This table shows the severity level required for Log to write a message to the listeners, given a particular DefaultSwitch setting.

DefaultSwitch Value Message severity required for output

Critical Critical

Error Critical or Error

Warning Critical , Error, or Warning

Information Critical , Error, Warning, or Information

Verbose Critical , Error, Warning, Information, or Verbose


ActivityTracing Start , Stop, Suspend, Resume, or Transfer

All All messages are allowed.

Off All messages are blocked.

Note

The WriteEntry and WriteException methods each have an overload that does not specify a severity level. The implicit severity level for the WriteEntry overload is
"Information", and the implicit severity level for the WriteException overload is "Error".

This table explains the log output shown in the previous example: with the default DefaultSwitch setting of "Information", only the second call to the WriteEntry
method and the call to the WriteException method produce log output.

To log only activity tracing events

1. Right-click app.config in the Solution Explorer and select Open.


-or-
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Locate the <switches> section, which is in the <system.diagnostics> section, which is in the top-level <configuration> section.
3. Find the element that adds DefaultSwitch to the collection of switches. It should look similar to this element:
<add name="DefaultSwitch" value="Information" />
4. Change the value of the value attribute to "ActivityTracing".
5. The content of the app.config file should be similar to the following XML:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.diagnostics>
<sources>
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="ActivityTracing" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
</sharedListeners>
</system.diagnostics>
</configuration>

6. Run the application in the debugger.


7. Press Button1.
The application writes the following information to the application's debug output and log file:
DefaultSource Start: 4 : Entering Button1_Click
DefaultSource Stop: 5 : Leaving Button1_Click
8. Close the application.
9. Change the value of the value attribute back to "Information".

Note

The DefaultSwitch switch setting controls only My.Application.Log. It does not change how the .NET Framework Trace and Debug classes behave.

Individual Filtering For My.Application.Log Listeners


The previous example shows how to change the filtering for all My.Application.Log output. This example demonstrates how to filter an individual log listener. By
default, an application has two listeners that write to the application's debug output and the log file.

The configuration file controls the behavior of the log listeners by allowing each one to have a filter, which is similar to a switch for My.Application.Log. A log listener
will output a message only if the message's severity is allowed by both the log's DefaultSwitch and the log listener's filter.

This example demonstrates how to configure filtering for a new debug listener and add it to the Log object. The default debug listener should be removed from the
Log object, so it is clear that the debug messages come from the new debug listener.

To log only activity-tracing events


1. Right-click app.config in the Solution Explorer and choose Open.
-or-
If there is no app.config file:
a. On the Project menu, choose Add New Item.
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
2. Right-click app.config in Solution Explorer. Choose Open.
3. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", which is under the <sources> section. The <sources> section
is under the <system.diagnostics> section, in the top-level <configuration> section.
4. Add this element to the <listeners> section:

<!-- Remove the default debug listener. -->


<remove name="Default"/>
<!-- Add a filterable debug listener. -->
<add name="NewDefault"/>

5. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
6. Add this element to that <sharedListeners> section:

<add name="NewDefault"
type="System.Diagnostics.DefaultTraceListener,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089,
processorArchitecture=MSIL">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Error" />
</add>

The EventTypeFilter filter takes one of the SourceLevels enumeration values as its initializeData attribute.
7. The content of the app.config file should be similar to the following XML:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.diagnostics>
<sources>
<!-- This section configures My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Remove the default debug listener. -->
<remove name="Default"/>
<!-- Add a filterable debug listener. -->
<add name="NewDefault"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
Microsoft.VisualBasic, Version=8.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<add name="NewDefault"
type="System.Diagnostics.DefaultTraceListener,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089,
processorArchitecture=MSIL">
<filter type="System.Diagnostics.EventTypeFilter"
initializeData="Error" />
</add>
</sharedListeners>
</system.diagnostics>
</configuration>

8. Run the application in the debugger.


9. Press Button1.
The application writes the following information to the application's log file:
Default Information: 0 : In Button1_Click
Default Error: 2 : Error in the application.
The application writes less information to the application's debug output because of the more restrictive filtering.
Default Error 2 Error
10. Close the application.

For more information about changing log settings after deployment, see Working with Application Logs in Visual Basic.
See Also
Tasks
Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic)
Walkthrough: Changing Where My.Application.Log Writes Information (Visual Basic)
Walkthrough: Creating Custom Log Listeners (Visual Basic)
How to: Write Log Messages (Visual Basic)
Concepts
Trace Switches
Logging Information from the Application (Visual Basic)

2014 Microsoft. All rights reserved.


Walkthrough: Creating Custom Log Listeners (Visual Basic)
Visual Studio 2012

This walkthrough demonstrates how to create a custom log listener and configure it to listen to the output of the My.Application.Log object.

Getting Started
Log listeners must inherit from the TraceListener class.

To create the listener

In your application, create a class named SimpleListener that inherits from TraceListener.

VB

Public Class SimpleListener


Inherits System.Diagnostics.TraceListener

<Security.Permissions.HostProtection(Synchronization:=True)>
Public Overloads Overrides Sub Write(ByVal message As String)
MsgBox("Write: " & message)
End Sub

<Security.Permissions.HostProtection(Synchronization:=True)>
Public Overloads Overrides Sub WriteLine(ByVal message As String)
MsgBox("WriteLine: " & message)
End Sub
End Class

The Write and WriteLine methods, required by the base class, call MsgBox to display their input.

The HostProtectionAttribute attribute is applied to the Write and WriteLine methods so that their attributes match the base class methods. The
HostProtectionAttribute attribute allows the host that runs the code to determine that the code exposes host-protection synchronization.

Note

The HostProtectionAttribute attribute is effective only on unmanaged applications that host the common language runtime and that implement host protection,
such as SQL Server.

To ensure that My.Application.Log uses your log listener, you should strongly name the assembly that contains your log listener.

The next procedure provides some simple steps for creating a strongly named log-listener assembly. For more information, see Creating and Using Strong-Named
Assemblies.

To strongly name the log-listener assembly

1. Have a project selected in Solution Explorer. On the Project menu, choose Properties. For more information, see Introduction to the Project Designer.

2. Click the Signing tab.

3. Select the Sign the assembly box.

4. Select <New> from the Choose a strong name key file drop-down list.

The Create Strong Name Key dialog box opens.

5. Provide a name for the key file in the Key file name box.

6. Enter a password in the Enter password and Confirm password boxes.

7. Click OK.

8. Rebuild the application.

Adding the Listener


Now that the assembly has a strong name, you need to determine the strong name of the listener so that My.Application.Log uses your log listener.

The format of a strongly named type is as follows.

<type name>, <assembly name>, <version number>, <culture>, <strong name>

To determine the strong name of the listener

The following code shows how to determine the strongly named type name for SimpleListener.
VB

Public Sub DisplaySimpleListenerStrongName()


Dim t As Type = GetType(SimpleListener)
MsgBox(t.FullName & ", " & t.Assembly.FullName)
End Sub

The strong name of the type depends on your project.

With the strong name, you can add the listener to the My.Application.Log log-listener collection.

To add the listener to My.Application.Log

1. Right-click on app.config in the Solution Explorer and choose Open.

-or-

If there is an app.config file:

a. On the Project menu, choose Add New Item.

b. From the Add New Item dialog box, choose Application Configuration File.

c. Click Add.

2. Locate the <listeners> section, in the <source> section with the name attribute "DefaultSource", located in the <sources> section. The <sources> section is
located in the <system.diagnostics> section, in the top-level <configuration> section.

3. Add this element to the <listeners> section:

<add name="SimpleLog" />

4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.

5. Add this element to that <sharedListeners> section:

<add name="SimpleLog" type="SimpleLogStrongName" />

Change the value of SimpleLogStrongName to be the strong name of the listener.

See Also
Tasks
How to: Log Exceptions in Visual Basic
How to: Write Log Messages (Visual Basic)
Walkthrough: Changing Where My.Application.Log Writes Information (Visual Basic)
Reference
Log
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


Troubleshooting: Log Listeners (Visual Basic)
Visual Studio 2012

You can use the My.Application.Log and My.Log objects to log information about events that occur in your application.

To determine which log listeners receive those messages, see Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic).

The Log object can use log filtering to limit the amount of information that it logs. If the filters are misconfigured, the logs might contain the wrong information. For more
information about filtering, see Walkthrough: Filtering My.Application.Log Output (Visual Basic).

However, if a log is configured incorrectly, you may need more information about its current configuration. You can get to this information through the log's advanced
TraceSource property.

To determine the log listeners for the Log object in code

1. Import the System.Diagnostics namespace at the beginning of the code file. For more information, see Imports Statement (.NET Namespace and Type).

VB

Imports System.Diagnostics

2. Create a function that returns a string consisting of information for each of the log's listeners.

VB

Function GetListeners(ByVal listeners As TraceListenerCollection) As String


Dim ret As String = ""
For Each listener As TraceListener In listeners
ret &= listener.Name
Dim listenerType As Type = listener.GetType
If listenerType Is GetType(DefaultTraceListener) Then
Dim tmp As DefaultTraceListener =
DirectCast(listener, DefaultTraceListener)
ret &= ": Writes to the debug output."
ElseIf listenerType Is GetType(Logging.FileLogTraceListener) Then
Dim tmp As Logging.FileLogTraceListener =
DirectCast(listener, Logging.FileLogTraceListener)
ret &= ": Log filename: " & tmp.FullLogFileName
ElseIf listenerType Is GetType(EventLogTraceListener) Then
Dim tmp As EventLogTraceListener =
DirectCast(listener, EventLogTraceListener)
ret &= ": Event log name: " & tmp.EventLog.Log
ElseIf listenerType Is GetType(XmlWriterTraceListener) Then
Dim tmp As Diagnostics.XmlWriterTraceListener =
DirectCast(listener, XmlWriterTraceListener)
ret &= ": XML log"
ElseIf listenerType Is GetType(ConsoleTraceListener) Then
Dim tmp As ConsoleTraceListener =
DirectCast(listener, ConsoleTraceListener)
ret &= ": Console log"
ElseIf listenerType Is GetType(DelimitedListTraceListener) Then
Dim tmp As DelimitedListTraceListener =
DirectCast(listener, DelimitedListTraceListener)
ret &= ": Delimited log"
Else
ret &= ": Unhandeled log type: " &
listenerType.ToString
End If
ret &= vbCrLf
Next

Return ret
End Function

3. Pass the collection of the log's trace listeners to the GetListeners function, and display the return value.

VB

Dim ListenerCollection As TraceListenerCollection


ListenerCollection = My.Application.Log.TraceSource.Listeners
Dim ListenersText As String = GetListeners(ListenerCollection)
MsgBox(ListenersText)

For more information, see TraceSource.

See Also
Tasks
Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic)
Reference
Log
Concepts
Working with Application Logs in Visual Basic

2014 Microsoft. All rights reserved.


Accessing User Data (Visual Basic)
Visual Studio 2012

This section contains topics dealing with the My.User object and tasks that you can accomplish with it.

The My.User object provides access to information about the logged-on user by returning an object that implements the IPrincipal interface.

Tasks

To See

Get the user's login name Name

Get the user's domain name, if the application uses Windows authentication CurrentPrincipal

Determine the user's role IsInRole

See Also
Reference
User

2014 Microsoft. All rights reserved.


Accessing Application Forms (Visual Basic)
Visual Studio 2012

The My.Forms object provides an easy way to access an instance of each Windows Form declared in the application's project. You can also use properties of the
My.Application object to access the application's splash screen and main form, and get a list of the application's open forms.

Tasks
The following table lists examples showing how to access an application's forms.

To See

Access one form from another form in an application. My.Forms Object

Display the titles of all the application's open forms. OpenForms

Update the splash screen with status information as the application starts. SplashScreen

See Also
Reference
My.Forms Object
OpenForms
SplashScreen

2014 Microsoft. All rights reserved.


Accessing Application Web Services (Visual Basic)
Visual Studio 2012

The My.WebServices object provides an instance of each Web service referenced by the current project. Each instance is instantiated on demand. You can access these
Web services through the properties of the My.WebServices object. The name of the property is the same as the name of the Web service that the property accesses. Any
class that inherits from SoapHttpClientProtocol is a Web service.

Tasks
The following table lists possible ways to access Web services referenced by an application.

To See

Call a Web service My.WebServices Object

Call a Web service asynchronously and handle an event when it completes How to: Call a Web Service Asynchronously (Visual Basic)

See Also
Reference
My.WebServices Object

2014 Microsoft. All rights reserved.


How to: Call a Web Service Asynchronously (Visual Basic)
Visual Studio 2012

This example attaches a handler to a Web service's asynchronous handler event, so that it can retrieve the result of an asynchronous method call. This example used the
DemoTemperatureService Web service at http://www.xmethods.net.

When you reference a Web service in your project in the Visual Studio Integrated Development Environment (IDE), it is added to the My.WebServices object, and the IDE
generates a client proxy class to access a specified Web service

The proxy class allows you to call the Web service methods synchronously, where your application waits for the function to complete. In addition, the proxy creates
additional members to help call the method asynchronously. For each Web service function, NameOfWebServiceFunction, the proxy creates a
NameOfWebServiceFunctionAsync subroutine, a NameOfWebServiceFunctionCompleted event, and a NameOfWebServiceFunctionCompletedEventArgs class. This example
demonstrates how to use the asynchronous members to access the getTemp function of the DemoTemperatureService Web service.

Note

This code does not work in Web applications, because ASP.NET does not support the My.WebServices object.

To call a Web service asynchronously

1. Reference the DemoTemperatureService Web service at http://www.xmethods.net. The address is

http://www.xmethods.net/sd/2001/DemoTemperatureService.wsdl

2. Add an event handler for the getTempCompleted event:

Private Sub getTempCompletedHandler(ByVal sender As Object,


ByVal e As net.xmethods.www.getTempCompletedEventArgs)

MsgBox("Temperature: " & e.Result)


End Sub

Note

You cannot use the Handles statement to associate an event handler with the My.WebServices object's events.

3. Add a field to track if the event handler has been added to the getTempCompleted event:

Private handlerAttached As Boolean = False

4. Add a method to add the event handler to the getTempCompleted event, if necessary, and to call the getTempAsynch method:

Sub CallGetTempAsync(ByVal zipCode As Integer)


If Not handlerAttached Then
AddHandler My.WebServices.
TemperatureService.getTempCompleted,
AddressOf Me.TS_getTempCompleted
handlerAttached = True
End If
My.WebServices.TemperatureService.getTempAsync(zipCode)
End Sub

To call the getTemp Web method asynchronously, call the CallGetTempAsync method. When the Web method finishes, its return value is passed to the
getTempCompletedHandler event handler.

See Also
Reference
My.WebServices Object
Concepts
Accessing Application Web Services (Visual Basic)

2014 Microsoft. All rights reserved.


Accessing Application Settings (Visual Basic)
Visual Studio 2012

This section contains topics describing the My.Settings object and the tasks it enables you to accomplish.

My.Settings
The properties of the My.Settings object provide access to your application's settings. To add or remove settings, use the Settings pane of the Project Designer.

The methods of the My.Settings object allow you to save the current user settings or revert the user settings to the last saved values.

Tasks
The following table lists examples showing how to access an application's forms.

To See

Update the value of a user setting How to: Change User Settings in Visual Basic

Display application and user settings in a property grid How to: Create Property Grids for User Settings in Visual Basic

Save updated user setting values How to: Persist User Settings in Visual Basic

Determine the values of user settings How to: Read Application Settings in Visual Basic

See Also
Tasks
How To: Read Settings at Run Time With C#
How To: Write User Settings at Run Time with C#
Reference
My.Settings Object
Concepts
Managing Application Settings
Managing Application Settings

2014 Microsoft. All rights reserved.


How to: Create Property Grids for User Settings in Visual Basic
Visual Studio 2012

You can create a property grid for user settings by populating a PropertyGrid control with the user setting properties of the My.Settings object.

Note

In order for this example to work, your application must have its user settings configured. For more information, see Managing Application Settings.

The My.Settings object exposes each setting as a property. The property name is the same as the setting name, and the property type is the same as the setting type. The
setting's Scope determines if the property is read-only; the property for an Application-scope setting is read-only, while the property for a User-scope setting is read-
write. For more information, see My.Settings Object.

Note

You cannot change or save the values of application-scope settings at run time. Application-scope settings can be changed only when creating the application (through
the Project Designer) or by editing the application's configuration file. For more information, see Managing Application Settings.

This example uses a PropertyGrid control to access the user-setting properties of the My.Settings object. By default, the PropertyGrid shows all the properties of the
My.Settings object. However, the user-setting properties have the UserScopedSettingAttribute attribute. This example sets the BrowsableAttributes property of the
PropertyGrid to UserScopedSettingAttribute to display only the user-setting properties.

To add a user setting property grid

1. Add the PropertyGrid control from the Toolbox to the design surface for your application, assumed here to be Form1.

The default name of the property-grid control is PropertyGrid1.

2. Double-click the design surface for Form1 to open the code for the form-load event handler.

3. Set the My.Settings object as the selected object for the property grid.

VB

PropertyGrid1.SelectedObject = My.Settings

4. Configure the property grid to show only the user settings.

VB

' Attribute for the user-scope settings.


Dim userAttr As New System.Configuration.UserScopedSettingAttribute
Dim attrs As New System.ComponentModel.AttributeCollection(userAttr)
PropertyGrid1.BrowsableAttributes = attrs

Note

To show only the application-scope settings, use the ApplicationScopedSettingAttribute attribute instead of UserScopedSettingAttribute.

Robust Programming
The application saves the user settings when the application shuts down. To save the settings immediately, call the My.Settings.Save method. For more information, see
How to: Persist User Settings in Visual Basic.

See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
Reference
My.Settings Object
Concepts
Managing Application Settings

2014 Microsoft. All rights reserved.


How to: Persist User Settings in Visual Basic
Visual Studio 2012

You can use the My.Settings.Save method to persist changes to the user settings.

Typically, applications are designed to persist the changes to the user settings when the application shuts down. This is because saving the settings can take, depending on
several factors, several seconds.

For more information, see My.Settings Object.

Note

Although you can change and save the values of user-scope settings at run time, application-scope settings are read-only and cannot be changed programmatically.
You can change application-scope settings when creating the application, through the Project Designer, or by editing the application's configuration file. For more
information, see Managing Application Settings.

Example
This example changes the value of the LastChanged user setting and saves that change by calling the My.Settings.Save method.

VB

Sub ChangeAndPersistSettings()
My.Settings.LastChanged = Today
My.Settings.Save()
End Sub

For this example to work, your application must have a LastChanged user setting, of type Date. For more information, see Managing Application Settings.

See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Change User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
Reference
My.Settings Object
Concepts
Managing Application Settings

2014 Microsoft. All rights reserved.


How to: Change User Settings in Visual Basic
Visual Studio 2012

You can change a user setting by assigning a new value to the setting's property on the My.Settings object.

The My.Settings object exposes each setting as a property. The property name is the same as the setting name, and the property type is the same as the setting type. The
setting's Scope determines if the property is read-only: The property for an Application-scope setting is read-only, while the property for a User-scope setting is read-
write. For more information, see My.Settings Object.

Note

Although you can change and save the values of user-scope settings at run time, application-scope settings are read-only and cannot be changed programmatically.
You can change application-scope settings when you create the application by using the Project Designer or by editing the application's configuration file. For more
information, see Managing Application Settings.

Example
This example changes the value of the Nickname user setting.

VB

Sub ChangeNickname(ByVal newNickname As String)


My.Settings.Nickname = newNickname
End Sub

For this example to work, your application must have a Nickname user setting, of type String.

The application saves the user settings when the application shuts down. To save the settings immediately, call the My.Settings.Save method. For more information, see
How to: Persist User Settings in Visual Basic.

See Also
Tasks
How to: Read Application Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
Reference
My.Settings Object
Concepts
Managing Application Settings

2014 Microsoft. All rights reserved.


How to: Read Application Settings in Visual Basic
Visual Studio 2012

You can read a user setting by accessing the setting's property on the My.Settings object.

The My.Settings object exposes each setting as a property. The property name is the same as the setting name, and the property type is the same as the setting type. The
setting's Scope indicates if the property is read-only; the property for an Application scope setting is read-only, while the property for a User scope setting is read-write.
For more information, see My.Settings Object.

Example
This example displays the value of the Nickname setting.

VB

Sub ShowNickname()
MsgBox("Nickname is " & My.Settings.Nickname)
End Sub

For this example to work, your application must have a Nickname setting, of type String. For more information, see Managing Application Settings.

See Also
Tasks
How to: Change User Settings in Visual Basic
How to: Persist User Settings in Visual Basic
How to: Create Property Grids for User Settings in Visual Basic
Reference
My.Settings Object
Concepts
Managing Application Settings

2014 Microsoft. All rights reserved.


Processing Drives, Directories, and Files (Visual Basic)
Visual Studio 2012

You can use Visual Basic to process drives, folders, and files with the My.Computer.FileSystem object, which provides better performance and is easier to use than
traditional methods such as the FileOpen and Write functions (although they are still available). The following sections discuss these methods in detail.

In This Section
File Access with Visual Basic
Discusses how to use the My.Computer.FileSystem object to work with files, drives, and folders.

Basics of .NET Framework File I/O and the File System (Visual Basic)
Provides an overview of file I/O concepts in the .NET Framework, including streams, isolated storage, file events, file attributes, and file access.

Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)


Demonstrates how to use the .NET Framework to manipulate files and folders.

Walkthrough: Manipulating Files and Directories in Visual Basic


Demonstrates how to use the My.Computer.FileSystem object to manipulate files and folders.

Related Sections
Program Structure and Code Conventions (Visual Basic)
Provides guidelines for the physical structure and appearance of programs.

FileSystem
Reference documentation for the My.Computer.FileSystem object and its members.

2014 Microsoft. All rights reserved.


File Access with Visual Basic
Visual Studio 2012

The My.Computer.FileSystem object provides tools for working with files and folders. Its properties, methods, and events allow you to create, copy, move, investigate,
and delete files and folders. My.Computer.FileSystem provides better performance than the legacy functions (FileOpen, FileClose, Input, InputString, LineInput, etc.)
that are provided by Visual Basic for backward compatibility.

In This Section
Reading from Files in Visual Basic
Lists topics dealing with using the My.Computer.FileSystem object to read from files

Writing to Files in Visual Basic


Lists topics dealing with using the My.Computer.FileSystem object to write to files

Creating, Deleting, and Moving Files and Directories in Visual Basic


Lists topics dealing with using the My.Computer.FileSystem object to creating, copying, deleting and moving files and folders.

Parsing Text Files with the TextFieldParser Object (Visual Basic)


Discusses how to use the TextFieldReader to parse text files such as logs.

File Encodings (Visual Basic)


Describes file encodings and their use.

Walkthrough: Manipulating Files and Directories in Visual Basic


Demonstrates how to create a utility that reports information about files and folders.

Troubleshooting: Reading from and Writing to Text Files (Visual Basic)


Lists common problems encountered when reading and writing to text files, and suggests remedies for each.

2014 Microsoft. All rights reserved.


Reading from Files in Visual Basic
Visual Studio 2012

This section explains how to perform tasks that are associated with reading from files.

In This Section
How to: Read From Text Files in Visual Basic
Demonstrates how to read from a text file.

How to: Read From Comma-Delimited Text Files in Visual Basic


Demonstrates how to read from a delimited text file.

How to: Read From Fixed-width Text Files in Visual Basic


Demonstrates how to read from a fixed-width text file.

How to: Read From Text Files with Multiple Formats in Visual Basic
Demonstrates how to read from a text file with multiple formats.

How to: Read From Binary Files in Visual Basic


Demonstrates how to read from a binary file.

How to: Read Text from Files with a StreamReader (Visual Basic)
Demonstrates how to use a StreamReader to read from a file.

Reference
FileSystem
Describes the My.Computer.FileSystem object and its members.

ReadAllText
Describes the ReadAllText method.

ReadAllBytes
Describes the ReadAllBytes method.

OpenTextFieldParser
Describes the OpenTextFieldParser method.

OpenTextFileReader
Describes the OpenTextFileReader method.

Related Sections
Storing Data to and Reading from the Clipboard (Visual Basic)
Explains how to perform tasks that are associated with My.Computer.Clipboard, such as reading data from or writing data to the Clipboard.

Parsing Text Files with the TextFieldParser Object (Visual Basic)


Provides an overview of reading text files with the TextFieldParser object.

Walkthrough: Manipulating Files and Directories in Visual Basic


Demonstrates how to use the My feature with files and directories.

Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)


Demonstrates how to use .NET Framework methods with files and directories.

2014 Microsoft. All rights reserved.


How to: Read From Text Files in Visual Basic
Visual Studio 2012

The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The file encoding can be specified if the contents of the file use an
encoding such as ASCII or UTF-8.

If you are reading from a file with extended characters, you will need to specify the file encoding.

Note

To read a file a single line of text at a time, use the OpenTextFileReader method of the My.Computer.FileSystem object. The OpenTextFileReader method returns a
StreamReader object. You can use the ReadLine method of the StreamReader object to read a file one line at a time. You can test for the end of the file using the
EndOfStream method of the StreamReader object.

To read from a text file

Use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string, supplying the path. The following example
reads the contents of test.txt into a string and then displays it in a message box.

VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

To read from a text file that is encoded

Use the ReadAllText method of the My.Computer.FileSytem object to read the contents of a text file into a string, supplying the path and file encoding type. The
following example reads the contents of the UTF32 file test.txt into a string and then displays it in a message box.

VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt",
System.Text.Encoding.UTF32)
MsgBox(fileReader)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

There is not enough memory to write the string to buffer (OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
FileSystem
ReadAllText
Concepts
File Encodings (Visual Basic)
Other Resources
Reading from Files in Visual Basic

2014 Microsoft. All rights reserved.


How to: Read From Comma-Delimited Text Files in Visual Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. The TextFieldType property defines whether it is a delimited
file or one with fixed-width fields of text.

To parse a comma delimited text file

1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")

2. Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the delimiter as ",".

VB

MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")

3. Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops through the file, displaying each field in
turn and reporting any fields that are formatted incorrectly.

VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.

VB

End While
End Using

Example
This example reads from the file test.txt.

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Fixed-width Text Files in Visual Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs.

The TextFieldType property defines whether the parsed file is a delimited file or one that has fixed-width fields of text. In a fixed-width text file, the field at the end can
have a variable width. To specify that the field at the end has a variable width, define it to have a width less than or equal to zero.

To parse a fixed-width text file

1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file test.log.

VB

Using Reader As New Microsoft.VisualBasic.


FileIO.TextFieldParser("C:\TestFolder\test.log")

2. Define the TextFieldType property as FixedWidth, defining the width and format. The following code defines the columns of text; the first is 5 characters wide, the
second 10, the third 11, and the fourth is of variable width.

VB

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)

3. Loop through the fields in the file. If any lines are corrupted, report an error and continue parsing.

VB

Dim currentRow As String()


While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.

VB

End While
End Using

Example
This example reads from the file test.log.

VB

Using Reader As New Microsoft.VisualBasic.FileIO.


TextFieldParser("C:\TestFolder\test.log")

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Text Files with Multiple Formats in Visual
Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. You can process a file with multiple formats by using the
PeekChars method to determine the format of each line as you parse through the file.

To parse a text file with multiple formats

1. Add a text file named testfile.txt to your project. Add the following content to the text file.

Err 1001 Cannot access resource.


Err 2014 Resource not found.
Acc 10/03/2009User1 Administrator.
Err 0323 Warning: Invalid access attempt.
Acc 10/03/2009User2 Standard user.
Acc 10/04/2009User2 Standard user.

2. Define the expected format and the format used when an error is reported. The last entry in each array is -1, therefore the last field is assumed to be of variable
width. This occurs when the last entry in the array is less than or equal to 0.

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}

3. Create a new TextFieldParser object, defining the width and format.

VB

Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")


MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat

4. Loop through the rows, testing for format before reading.

VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()

5. Write errors to the console.

VB

Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid.")
End Try
End While
End Using

Example
Following is the complete example that reads from the file testfile.txt.

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat
Dim currentRow As String()
While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()
Catch ex As FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Console.ReadLine()

Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
Reference
TextFieldParser
PeekChars
MalformedLineException
WriteAllText
EndOfData
TextFieldType
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Binary Files in Visual Basic
Visual Studio 2012

The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.

To read from a binary file

Use the ReadAllBytes method, which returns the contents of a file as a byte array. This example reads from the file C:/Documents and
Settings/selfportrait.jpg.

VB

Dim bytes = My.Computer.FileSystem.ReadAllBytes(


"C:/Documents and Settings/selfportrait.jpg")
PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))

For large binary files, you can use the Read method of the FileStream object to read from the file only a specified amount at a time. You can then limit how much of
the file is loaded into memory for each read operation. The following code example copies a file and allows the caller to specify how much of the file is read into
memory per read operation.

VB

' This method does not trap for exceptions. If an exception is


' encountered opening the file to be copied or writing to the
' destination location, then the exception will be thrown to
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
ByVal copyPath As String,
ByVal bufferSize As Integer,
ByVal overwrite As Boolean)

Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then


My.Computer.FileSystem.DeleteFile(copyPath)
End If

' Adjust array length for VB array declaration.


Dim bytes = New Byte(bufferSize - 1) {}

While inputFile.Read(bytes, 0, bufferSize) > 0


My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
End While

inputFile.Close()
End Sub

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

There is not enough memory to write the string to buffer (OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
ReadAllBytes
WriteAllBytes
Other Resources
Reading from Files in Visual Basic
Storing Data to and Reading from the Clipboard (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read Text from Files with a StreamReader (Visual
Basic)
Visual Studio 2012

The My.Computer.FileSystem object provides methods to open a TextReader and a TextWriter. These methods, OpenTextFileWriter and OpenTextFileReader, are
advanced methods that do not appear in IntelliSense unless you select the All tab.

To read a line from a file with a text reader

Use the OpenTextFileReader method to open the TextReader, specifying the file. This example opens the file named testfile.txt, reads a line from it, and
displays the line in a message box.

VB

Dim fileReader As System.IO.StreamReader


fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)

Robust Programming
The file that is read must be a text file.

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

Security
To read from a file, your assembly requires a privilege level granted by the FileIOPermission class. If you are running in a partial-trust context, the code might throw an
exception due to insufficient privileges. For more information, see Code Access Security Basics. The user also needs access to the file. For more information, see ACL
Technology Overview.

See Also
Reference
FileSystem
OpenFileDialog
OpenTextFileWriter
OpenTextFileReader
Other Resources
SaveFileDialog Component (Windows Forms)
Reading from Files in Visual Basic

2014 Microsoft. All rights reserved.


Writing to Files in Visual Basic
Visual Studio 2012

This section explains how to perform tasks that involve writing to files.

In This Section
How to: Write Text to Files in Visual Basic
Demonstrates how to write to text files.

How to: Append to Text Files in Visual Basic


Demonstrates how to append text to a text file.

How to: Write to Binary Files in Visual Basic


Demonstrates how to write to a binary file.

How to: Write Text to Files in the My Documents Directory in Visual Basic
Demonstrates how to create and write to a new text file in the My Documents directory.

How to: Write Text to Files with a StreamWriter in Visual Basic


Demonstrates how to write to a file with a StreamWriter object.

Reference
FileSystem
Describes the My.Computer.FileSystem object and its methods and properties.

OpenTextFileWriter
Describes the OpenTextFileWriter method.

WriteAllBytes
Describes the WriteAllBytes method.

WriteAllText
Describes the WriteAllText method.

Related Sections
Reading from Files in Visual Basic
Explains how to perform tasks that involve reading from files.

Creating, Deleting, and Moving Files and Directories in Visual Basic


Explains how to perform tasks that involve creating, deleting, moving, and renaming files and directories.

Storing Data to and Reading from the Clipboard (Visual Basic)


Explains how to perform tasks that are associated with My.Computer.Clipboard, such as reading data from or writing data to the Clipboard.

File Encodings (Visual Basic)


Provides an overview of file encodings.

2014 Microsoft. All rights reserved.


How to: Write Text to Files in Visual Basic
Visual Studio 2012

The WriteAllText method can be used to write text to files. If the specified file does not exist, it is created.

Procedure

To write text to a file

Use the WriteAllText method to write text to a file, specifying the file and text to be written. This example writes the line "This is new text." to the file named
test.txt, appending the text to any existing text in the file.

VB

My.Computer.FileSystem.WriteAllText("C:\TestFolder1\test.txt",
"This is new text to be added.",True)

To write a series of strings to a file

Loop through the string collection. Use the WriteAllText method to write text to a file, specifying the target file and string to be added and setting append to
True.

This example writes the names of the files in the Documents and Settings directory to FileList.txt, inserting a carriage return between each for better
readability.

VB

For Each foundFile As String In


My.Computer.FileSystem.GetFiles("C:\Documents and Settings")
foundFile = foundFile & vbCrLf
My.Computer.FileSystem.WriteAllText(
"C:\Documents and Settings\FileList.txt", foundFile, True)
Next

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The disk is full, and the call to WriteAllText fails (IOException).

If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see Code Access Security Basics.

See Also
Tasks
How to: Read From Text Files in Visual Basic
Reference
FileSystem
WriteAllText

2014 Microsoft. All rights reserved.


How to: Append to Text Files in Visual Basic
Visual Studio 2012

The WriteAllText method can be used to append to a text file by specifying that the append parameter is set to True.

To append to a text file

Use the WriteAllText method, specifying the target file and string to be appended and setting the append parameter to True.

This example writes the string "This is a test string." to the file named Testfile.txt.

VB

Dim inputString As String = "This is a test string."


My.Computer.FileSystem.WriteAllText(
"C://testfile.txt", inputString, True)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

See Also
Reference
WriteAllText
FileSystem
Other Resources
Writing to Files in Visual Basic

2014 Microsoft. All rights reserved.


How to: Write to Binary Files in Visual Basic
Visual Studio 2012

The WriteAllBytes method writes data to a binary file. If the append parameter is True, it will append the data to the file; otherwise data in the file is overwritten.

If the specified path excluding the file name is not valid, a DirectoryNotFoundException exception will be thrown. If the path is valid but the file does not exist, the file will be
created.

To write to a binary file

Use the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named
CollectedData.dat.

VB

Dim CustomerData As Byte() = (From c In customerQuery).ToArray()

My.Computer.FileSystem.WriteAllBytes(
"C:\MyDocuments\CustomerData", CustomerData, True)

Robust Programming
The following conditions may create an exception:

The path is not valid for one of the following reasons: it is a zero-length string; it contains only white space; or it contains invalid characters. (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

File points to a path that does not exist (FileNotFoundException or DirectoryNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

See Also
Tasks
How to: Write Text to Files in Visual Basic
Reference
WriteAllBytes

2014 Microsoft. All rights reserved.


How to: Write Text to Files in the My Documents Directory in
Visual Basic
Visual Studio 2012

The My.Computer.FileSystem.SpecialDirectories object allows you to access special directories, such as the MyDocuments directory.

Procedure

To write new text files in the My Documents directory

1. Use the My.Computer.FileSystem.SpecialDirectories.MyDocuments property to supply the path.

VB

Dim filePath As String


filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")

2. Use the WriteAllText method to write text to the specified file.

VB

My.Computer.FileSystem.WriteAllText(filePath, "some text", True)

Example
VB

Try
Dim filePath As String
filePath = System.IO.Path.Combine(
My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
My.Computer.FileSystem.WriteAllText(filePath, "some text", False)
Catch fileException As Exception
Throw fileException
End Try

Compiling the Code


Replace test.txt with the name of the file you want to write to.

Robust Programming
This code rethrows all the exceptions that may occur when writing text to the file. You can reduce the likelihood of exceptions by using Windows Forms controls such as
the OpenFileDialog and the SaveFileDialog components that limit the user choices to valid file names. Using these controls is not foolproof, however. The file system can
change between the time the user selects a file and the time that the code executes. Exception handling is therefore nearly always necessary when with working with files.

Security
If you are running in a partial-trust context, the code might throw an exception due to insufficient privileges. For more information, see Code Access Security Basics.

This example creates a new file. If an application needs to create a file, that application needs Create permission for the folder. Permissions are set using access control
lists. If the file already exists, the application needs only Write permission, a lesser privilege. Where possible, it is more secure to create the file during deployment, and
only grant Read privileges to a single file, rather than to grant Create privileges for a folder. Also, it is more secure to write data to user folders than to the root folder
or the Program Files folder. For more information, see ACL Technology Overview.

See Also
Reference
PathCombine
Computer
FileSystem
WriteAllText
SpecialDirectories

2014 Microsoft. All rights reserved.


How to: Write Text to Files with a StreamWriter in Visual Basic
Visual Studio 2012

This example opens a StreamWriter object with the My.Computer.FileSystem.OpenTextFileWriter method and uses it to write a string to a text file with the WriteLine
method of the StreamWriter class.

Example
VB

Dim file As System.IO.StreamWriter


file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()

Robust Programming
The following conditions may cause an exception:

The file exists and is read-only (IOException).

The disk is full (IOException).

The pathname is too long (PathTooLongException).

Security
This example creates a new file, if the file does not already exist. If an application needs to create a file, that application needs Create access for the folder. If the file
already exists, the application needs only Write access, a lesser privilege. Where possible, it is more secure to create the file during deployment, and only grant Read
access to a single file, rather than Create access for a folder.

See Also
Tasks
How to: Read From Text Files in Visual Basic
Reference
StreamWriter
OpenTextFileWriter
Other Resources
Writing to Files in Visual Basic

2014 Microsoft. All rights reserved.


Creating, Deleting, and Moving Files and Directories in Visual
Basic
Visual Studio 2012

This section lists tasks associated with creating, deleting, moving, and renaming files and directories in Visual Basic.

In This Section
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
Demonstrates how to copy files with a specific file name pattern, such as only .txt files, to a directory.

How to: Create a Copy of a File in the Same Directory in Visual Basic
Demonstrates how to create a copy of a file in the same directory.

How to: Create a Copy of a File in a Different Directory in Visual Basic


Demonstrates how to copy a file to another directory.

How to: Create a File in Visual Basic


Demonstrates how to create a file.

How to: Delete a File in Visual Basic


Demonstrates how to delete a file.

How to: Find Files with a Specific Pattern in Visual Basic


Demonstrates how to list only files with a specific file name pattern in a directory.

How to: Move a File in Visual Basic


Demonstrates how to move a file to a different directory.

How to: Rename a File in Visual Basic


Demonstrates how to rename a file.

How to: Copy a Directory to Another Directory in Visual Basic


Demonstrates how to copy a directory to another location.

How to: Create a Directory in Visual Basic


Demonstrates how to create a directory.

How to: Find Subdirectories with a Specific Pattern in Visual Basic


Demonstrates how to list directories with a specific pattern in their name.

How to: Get the Collection of Files in a Directory in Visual Basic


Demonstrates how to list the files in a directory.

How to: Retrieve the Contents of the My Documents Directory in Visual Basic
Demonstrates how to read from special directories.

How to: Parse File Paths in Visual Basic


Demonstrates how to use My methods to combine file paths.

Reference
FileSystem
Describes the My.Computer.FileSystem object and its members.

CombinePath
Describes the CombinePath method.

CopyDirectory
Describes the CopyDirectory method.

CopyFile
Describes the CopyFile method.

CreateDirectory
Describes the CreateDirectory method.

DeleteDirectory
Describes the DeleteDirectory method.

DeleteFile
Describes the DeleteFile method.

GetParentPath
Describes the GetParentPath method.

MoveDirectory
Describes the MoveDirectory method.
MoveFile
Describes the MoveFile method.

RenameDirectory
Describes the RenameDirectory method.

RenameFile
Describes the RenameFile method.

SpecialDirectories
Describes the SpecialDirectories object.

Related Sections
Reading from Files in Visual Basic
Lists tasks associated with reading from files.

Writing to Files in Visual Basic


Lists tasks involving writing to files.

2014 Microsoft. All rights reserved.


How to: Copy Files with a Specific Pattern to a Directory in
Visual Basic
Visual Studio 2012

The GetFiles method returns a read-only collection of strings representing the path names for the files. You can use the wildCards parameter to specify a specific pattern.

An empty collection is returned if no matching files are found.

You can use the CopyFile method to copy the files to a directory.

To copy files with a specific pattern to a directory

1. Use the GetFiles method to return the list of files. This example returns all .rtf files in the specified directory.

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")

2. Use the CopyFile method to copy the files. This example copies the files to the directory named testdirectory.

VB

My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & My.Computer.FileSystem.GetName(foundFile))

3. Close the For statement with a Next statement.

VB

Next

Example
The following example, which presents the above snippets in complete form, copies all .rtf files in the specified directory to the directory named testdirectory.

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")

My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & foundFile)


Next

Security
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The directory does not exist (DirectoryNotFoundException).

The directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException). The user lacks necessary permissions (UnauthorizedAccessException).

See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
CopyFile
GetFiles

2014 Microsoft. All rights reserved.


How to: Create a Copy of a File in the Same Directory in Visual
Basic
Visual Studio 2012

Use the My.Computer.FileSystem.CopyFile method to copy files. The parameters allow you to overwrite existing files, rename the file, show the progress of the
operation, and allow the user to cancel the operation.

To create a copy of a file in the same folder

Use the CopyFile method, supplying the target file and the location. The following example creates a copy of test.txt called test2.txt.

VB

My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt",
"C:\TestFolder\test2.txt", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)

To create a copy of a file in the same folder, overwriting existing files

Use the CopyFile method, supplying the target file and location, and setting overwrite to True. The following example creates a copy of test.txt called test2.txt
and overwrites any existing files by that name.

VB

My.Computer.FileSystem.CopyFile("C:\TestFolder\test.txt",
"C:\TestFolder\test2.txt", True)

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The system could not retrieve the absolute path (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

The combined path points to an existing directory (IOException).

The destination file exists and overwrite is set to False (IOException).

The user does not have sufficient permissions to access the file (IOException).

A file in the target folder with the same name is in use (IOException).

A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

ShowUI is set to True, onUserCancel is set to ThrowException, and the user has cancelled the operation (OperationCanceledException).

ShowUI is set to True, onUserCancel is set to ThrowException, and an unspecified I/O error occurs (OperationCanceledException).

The path exceeds the system-defined maximum length (PathTooLongException).

The user does not have required permission (UnauthorizedAccessException).

The user lacks necessary permissions to view the path (SecurityException).

See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
FileSystem
CopyFile
UICancelOption

2014 Microsoft. All rights reserved.


How to: Create a Copy of a File in a Different Directory in
Visual Basic
Visual Studio 2012

The My.Computer.FileSystem.CopyFile method allows you to copy files. Its parameters provide the ability to overwrite existing files, rename the file, show the progress of
the operation, and allow the user to cancel the operation.

To copy a text file to another folder

Use the CopyFile method to copy a file, specifying a source file and the target directory. Theoverwrite parameter allows you to specify whether or not to overwrite
existing files. The following code examples demonstrate how to use CopyFile.

VB

' Copy the file to a new location without overwriting existing file.
My.Computer.FileSystem.CopyFile(
"C:\UserFiles\TestFiles\testFile.txt",
"C:\UserFiles\TestFiles2\testFile.txt")

' Copy the file to a new folder, overwriting existing file.


My.Computer.FileSystem.CopyFile(
"C:\UserFiles\TestFiles\testFile.txt",
"C:\UserFiles\TestFiles2\testFile.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

' Copy the file to a new folder and rename it.


My.Computer.FileSystem.CopyFile(
"C:\UserFiles\TestFiles\testFile.txt",
"C:\UserFiles\TestFiles2\NewFile.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The system could not retrieve the absolute path (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

The combined path points to an existing directory (IOException).

The destination file exists and overwrite is set to False (IOException).

The user does not have sufficient permissions to access the file (IOException).

A file in the target folder with the same name is in use (IOException).

A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

ShowUI is set to True, onUserCancel is set to ThrowException, and the user has cancelled the operation (OperationCanceledException).

ShowUI is set to True, onUserCancel is set to ThrowException, and an unspecified I/O error occurs (OperationCanceledException).

The path exceeds the system-defined maximum length (PathTooLongException).

The user does not have required permission (UnauthorizedAccessException).

The user lacks necessary permissions to view the path (SecurityException).

See Also
Tasks
How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Copy a Directory to Another Directory in Visual Basic
How to: Rename a File in Visual Basic
Reference
FileSystem
CopyFile
UICancelOption

2014 Microsoft. All rights reserved.


How to: Create a File in Visual Basic
Visual Studio 2012

This example creates an empty text file at the specified path using the Create method in the File class.

Example
VB

Imports System
Imports System.IO
Imports System.Text

Module Module1

Sub Main()
Dim path As String = "c:\temp\MyTest.txt"

' Create or overwrite the file.


Dim fs As FileStream = File.Create(path)

' Add text to the file.


Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
fs.Write(info, 0, info.Length)
fs.Close()
End Sub

End Module

Compiling the Code


Use the file variable to write to the file.

Robust Programming
If the file already exists, it is replaced.

The following conditions may cause an exception:

The path name is malformed. For example, it contains illegal characters or is only white space (ArgumentException).

The path is read-only (IOException).

The path name is Nothing (ArgumentNullException).

The path name is too long (PathTooLongException).

The path is invalid (DirectoryNotFoundException).

The path is only a colon ":" (NotSupportedException).

Security
A SecurityException may be thrown in partial-trust environments.

The call to the Create method requires FileIOPermission.

An UnauthorizedAccessException is thrown if the user does not have permission to create the file.

See Also
Reference
System.IO
Create
Concepts
Using Libraries from Partially Trusted Code
Code Access Security Basics

2014 Microsoft. All rights reserved.


How to: Delete a File in Visual Basic
Visual Studio 2012

The DeleteFile method of the My.Computer.FileSystem object allows you to delete a file. Among the options it offers are: whether to send the deleted file to the Recycle
Bin, whether to ask the user to confirm that the file should be deleted, and what to do when the user cancels the operation.

To delete a text file

Use the DeleteFile method to delete the file. The following code demonstrates how to delete the file named test.txt.

VB

My.Computer.FileSystem.DeleteFile("C:\test.txt")

To delete a text file and ask the user to confirm that the file should be deleted

Use the DeleteFile method to delete the file, setting showUI to AllDialogs. The following code demonstrates how to delete the file named test.txt and allow the
user to confirm that the file should be deleted.

VB

My.Computer.FileSystem.DeleteFile("C:\test.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.RecycleOption.DeletePermanently,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

To delete a text file and send it to the Recycle Bin

Use the DeleteFile method to delete the file, specifying SendToRecycleBin for the recycle parameter. The following code demonstrates how to delete the file
named test.txt and send it to the Recycle Bin.

VB

My.Computer.FileSystem.DeleteFile("C:\test.txt",
Microsoft.VisualBasic.FileIO.UIOption.AllDialogs,
Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The file is in use (IOException).

The user lacks necessary permissions to view the path (SecurityException).

The file does not exist (FileNotFoundException).

The user does not have permission to delete the file, or the file is read-only (UnauthorizedAccessException).

A partial-trust situation exists in which the user does not have sufficient permissions (SecurityException).

The user cancelled the operation and onUserCancel is set to ThrowException (OperationCanceledException).

See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
UICancelOption
FileSystem
UIOption
RecycleOption

2014 Microsoft. All rights reserved.


How to: Find Files with a Specific Pattern in Visual Basic
Visual Studio 2012

The GetFiles method returns a read-only collection of strings representing the path names for the files. You can use the wildCards parameter to specify a specific pattern. If
you would like to include subdirectories in the search, set the searchType parameter to SearchOption.SearchAllSubDirectories.

An empty collection is returned if no files matching the specified pattern are found.

Note

For information about returning a file list by using the DirectoryInfo class of the System.IO namespace, see GetFiles.

To find files with a specified pattern

Use the GetFiles method, supplying the name and path of the directory you want to search and specifying the pattern. The following example returns all files with
the extension .dll in the directory and adds them to ListBox1.

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.dll")

Listbox1.Items.Add(foundFile)
Next

Security
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

directory does not exist (DirectoryNotFoundException).

directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user lacks necessary permissions (UnauthorizedAccessException).

See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
GetFiles

2014 Microsoft. All rights reserved.


How to: Move a File in Visual Basic
Visual Studio 2012

The My.Computer.FileSystem.MoveFile method can be used to move a file to another folder. If the target structure does not exist, it will be created.

To move a file

Use the MoveFile method to move the file, specifying the file name and location for both the source file and the target file. This example moves the file named
test.txt from TestDir1 to TestDir2. Note that the target file name is specified even though it is the same as the source file name.

VB

My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt",
"C:\TestDir2\test.txt")

To move a file and rename it

Use the MoveFile method to move the file, specifying the source file name and location, the target location, and the new name at the target location. This example
moves the file named test.txt from TestDir1 to TestDir2 and renames it nexttest.txt.

VB

My.Computer.FileSystem.MoveFile("C:\TestDir1\test.txt",
"C:\TestDir2\nexttest.txt",
FileIO.UIOption.AllDialogs,
FileIO.UICancelOption.ThrowException)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

destinationFileName is Nothing or an empty string (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

The combined path points to an existing directory, the destination file exists and overwrite is set to False, a file in the target directory with the same name is in
use, or the user does not have sufficient permissions to access the file (IOException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

showUI is set to True, onUserCancel is set to ThrowException, and either the user has cancelled the operation or an unspecified I/O error occurs
(OperationCanceledException).

The path exceeds the system-defined maximum length (PathTooLongException).

The user lacks necessary permissions to view the path (SecurityException).

The user does not have required permission (UnauthorizedAccessException).

See Also
Tasks
How to: Rename a File in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
MoveFile

2014 Microsoft. All rights reserved.


How to: Rename a File in Visual Basic
Visual Studio 2012

Use the RenameFile method of the My.Computer.FileSystem object to rename a file by supplying the current location, file name, and the new file name. This method
cannot be used to move a file; use the MoveFile method to move and rename the file.

To rename a file

Use the My.Computer.FileSystem.RenameFile method to rename a file. This example renames the file named Test.txt to SecondTest.txt.

VB

' Change "c:\test.txt" to the path and filename for the file that
' you want to rename.
My.Computer.FileSystem.RenameFile("C:\Test.txt", "SecondTest.txt")

This code example is also available as an IntelliSense code snippet. In the code snippet picker, the snippet is located in File system - Processing Drives, Folders, and
Files. For more information, see Code Snippets.

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

newName contains path information (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

newName is Nothing or an empty string (ArgumentNullException).

The source file is not valid or does not exist (FileNotFoundException).

There is an existing file or directory with the name specified in newName (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user does not have the required permission (UnauthorizedAccessException).

See Also
Tasks
How to: Move a File in Visual Basic
How to: Create a Copy of a File in the Same Directory in Visual Basic
How to: Create a Copy of a File in a Different Directory in Visual Basic
Reference
RenameFile
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic

2014 Microsoft. All rights reserved.


How to: Copy a Directory to Another Directory in Visual Basic
Visual Studio 2012

Use the CopyDirectory method to copy a directory to another directory. This method copies the contents of the directory as well as the directory itself. If the target
directory does not exist, it will be created. If a directory with the same name exists in the target location and overwrite is set to False, the contents of the two directories will
be merged. You can specify a new name for the directory during the operation.

When copying files within a directory, exceptions may be thrown that are caused by specific file, such as a file existing during a merge while overwrite is set to False. When
such exceptions are thrown, they are consolidated into a single exception, whose Data property holds entries in which the file or directory path is the key and the specific
exception message is contained in the corresponding value.

To copy a directory to another directory

Use the CopyDirectory method, specifying source and destination directory names. The following example copies the directory named TestDirectory1 into
TestDirectory2, overwriting existing files.

VB

My.Computer.FileSystem.CopyDirectory("C:\TestDirectory1", "C:\TestDirectory2", True)

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in File system - Processing Drives, Folders, and Files.
For more information, see Code Snippets.

Robust Programming
The following conditions may cause an exception:

The new name specified for the directory contains a colon (:) or slash (\ or /) (ArgumentException).

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

destinationDirectoryName is Nothing or an empty string (ArgumentNullException)

The source directory does not exist (DirectoryNotFoundException).

The source directory is a root directory (IOException).

The combined path points to an existing file (IOException).

The source path and target path are the same (IOException).

ShowUI is set to UIOption.AllDialogs and the user cancels the operation, or one or more files in the directory cannot be copied (OperationCanceledException).

The operation is cyclic (InvalidOperationException).

The path contains a colon (:) (NotSupportedException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

A destination file exists but cannot be accessed (UnauthorizedAccessException).

See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
CopyDirectory

2014 Microsoft. All rights reserved.


How to: Create a Directory in Visual Basic
Visual Studio 2012

Use the CreateDirectory method of the My.Computer.FileSystem object to create directories.

If the directory already exists, no exception is thrown.

To create a directory

Use the CreateDirectory method by specifying the full path of the location where the directory should be created. This example creates the directory NewDirectory
in C:\Documents and Settings\All Users\Documents.

VB

My.Computer.FileSystem.CreateDirectory(
"C:\Documents and Settings\All Users\Documents\NewDirectory")

Robust Programming
The following conditions may cause an exception:

The directory name is malformed. For example, it contains illegal characters or is only white space (ArgumentException).

The parent directory of the directory to be created is read-only (IOException).

The directory name is Nothing (ArgumentNullException).

The directory name is too long (PathTooLongException).

The directory name is a colon ":" (NotSupportedException).

The user does not have permission to create the directory (UnauthorizedAccessException).

The user lacks permissions in a partial-trust situation (SecurityException).

See Also
Reference
CreateDirectory
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic

2014 Microsoft. All rights reserved.


How to: Find Subdirectories with a Specific Pattern in Visual
Basic
Visual Studio 2012

The GetDirectories method returns a read-only collection of strings representing the path names for the subdirectories in a directory. You can use the wildCards parameter
to specify a specific pattern. If you would like to include the contents of subdirectories in the search, set the searchType parameter to
SearchOption.SearchAllSubDirectories.

An empty collection is returned if no directories matching the specified pattern are found.

To find subdirectories with a specific pattern

Use the GetDirectories method, supplying the name and path of the directory you want to search. The following example returns all the directories in the directory
structure that contain the word "Logs" in their name, and adds them to ListBox1.

VB

For Each foundDirectory As String In


My.Computer.FileSystem.GetDirectories(
My.Computer.FileSystem.SpecialDirectories.MyDocuments,
FileIO.SearchOption.SearchTopLevelOnly,
"*Logs*")

ListBox1.Items.Add(foundDirectory)
Next

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

One or more of the specified wildcard characters is Nothing, an empty string, or contains only spaces (ArgumentNullException).

directory does not exist (DirectoryNotFoundException).

directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user lacks necessary permissions (UnauthorizedAccessException).

See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
Reference
GetDirectories

2014 Microsoft. All rights reserved.


How to: Get the Collection of Files in a Directory in Visual Basic
Visual Studio 2012

The GetFiles method returns a read-only collection of strings representing the name of the files within a directory. You can use the wildCards parameter to specify a specific
pattern. To include subdirectories in the search, set the searchType parameter to SearchOption.SearchAllSubDirectories.

An empty collection is returned if no files matching the specified pattern are found.

To list files in a directory

Use the GetFiles method, supplying the name and path of the directory to search. The following example returns all files in the directory and adds them to
ListBox1.

VB

For Each foundFile As String In My.Computer.FileSystem.GetFiles(


My.Computer.FileSystem.SpecialDirectories.MyDocuments)

listBox1.Items.Add(foundFile)
Next

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(starts with \\.\) (ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

directory does not exist (DirectoryNotFoundException).

directory points to an existing file (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

The user lacks necessary permissions to view the path (SecurityException).

The user lacks necessary permissions (UnauthorizedAccessException).

See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Reference
GetFiles

2014 Microsoft. All rights reserved.


How to: Retrieve the Contents of the My Documents Directory
in Visual Basic
Visual Studio 2012

The SpecialDirectories object can be used to read from many of the All Users directories, such as My Documents or Desktop.

To read from the My Documents folder

Use the ReadAllText method to read the text from each file in a specific directory. The following code specifies a directory and file and then uses ReadAllText to
read them into the string named patients.

VB

Dim path As String


Dim patients As String
path = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\" & "Patients.txt"
patients = My.Computer.FileSystem.ReadAllText(path)

See Also
Reference
SpecialDirectories
ReadAllText

2014 Microsoft. All rights reserved.


How to: Parse File Paths in Visual Basic
Visual Studio 2012

The FileSystem object offers a number of useful methods when parsing file paths.

The CombinePath method takes two paths and returns a properly formatted combined path.

The GetParentPath method returns the absolute path of the parent of the provided path.

The GetFileInfo method returns a FileInfo object that can be queried to determine the file's properties, such as its name and path.

Do not make decisions about the contents of the file based on the file name extension. For example, the file Form1.vb may not be a Visual Basic source file.

To determine a file's name and path

Use the DirectoryName and Name properties of the FileInfo object to determine a file's name and path. This example determines the name and path and displays
them.

VB

Dim testFile As System.IO.FileInfo


testFile = My.Computer.FileSystem.GetFileInfo("C:\TestFolder1\test1.txt")
Dim folderPath As String = testFile.DirectoryName
MsgBox(folderPath)
Dim fileName As String = testFile.Name
MsgBox(fileName)

To combine a file's name and directory to create the full path

Use the CombinePath method, supplying the directory and name. This example takes the strings folderPath and fileName created in the previous example,
combines them, and displays the result.

VB

Dim fullPath As String


fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName)
MsgBox(fullPath)

See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
FileSystem
CombinePath
FileInfo
GetFileInfo

2014 Microsoft. All rights reserved.


Parsing Text Files with the TextFieldParser Object (Visual Basic)
Visual Studio 2012

The TextFieldParser object allows you to parse and process very large file that are structured as delimited-width columns of text, such as log files or legacy database
information. Parsing a text file with TextFieldParser is similar to iterating over a text file, while the parse method to extract fields of text is similar to string manipulation
methods used to tokenize delimited strings.

Parsing Different Types of Text Files


Text files may have fields of various width, delimited by a character such as a comma or a tab space. Define TextFieldType and the delimiter, as in the following
example, which uses the SetDelimiters method to define a tab-delimited text file:

VB

testReader.SetDelimiters(vbTab)

Other text files may have field widths that are fixed. In such cases, you need to define the TextFieldType as FixedWidth and define the widths of each field, as in the
following example. This example uses the SetFieldWidths method to define the columns of text: the first column is 5 characters wide, the second is 10, the third is 11,
and the fourth is of variable width.

VB

testReader.SetFieldWidths(5, 10, 11, -1)


testReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth

Once the format is defined, you can loop through the file, using the ReadFields method to process each line in turn.

If a field does not match the specified format, a MalformedLineException exception is thrown. When such exceptions are thrown, the ErrorLine and ErrorLineNumber
properties hold the text causing the exception and the line number of that text.

Parsing Files with Multiple Formats


The PeekChars method of the TextFieldParser object can be used to check each field before reading it, allowing you to define multiple formats for the fields and react
accordingly. For more information, see How to: Read From Text Files with Multiple Formats in Visual Basic.

See Also
Tasks
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
OpenTextFieldParser
TextFieldParser
PeekChars
ReadFields
CommentTokens
Delimiters
ErrorLine
ErrorLineNumber
FieldWidths
HasFieldsEnclosedInQuotes
LineNumber
TextFieldType
TrimWhiteSpace
SetDelimiters
SetFieldWidths

2014 Microsoft. All rights reserved.


File Encodings (Visual Basic)
Visual Studio 2012

File encodings, also known as character encodings, specify how to represent characters when text processing. One encoding may be preferable over another in terms of
which language characters it can or cannot handle, although Unicode is usually preferred.

When reading from or writing to files, improperly matching file encodings may result in exceptions or incorrect results.

Types of Encodings
Unicode is the preferred encoding when working with files. Unicode is a worldwide character-encoding standard that uses 16-bit code values to represent all the
characters used in modern computing, including technical symbols and special characters used in publishing.

Previous character-encoding standards consisted of traditional character sets, such as the Windows ANSI character set that uses 8-bit code values, or combinations of 8-
bit values, to represent the characters used in a specific language or geographical region.

Encoding Class
The Encoding class represents a character encoding. This table lists the type of encodings available and describes each.

Name Description

ASCIIEncoding Represents an ASCII character encoding of Unicode characters.

UnicodeEncoding Represents a UTF-16 encoding of Unicode characters.

UTF32Encoding Represents a UTF-32 encoding of Unicode characters.

UTF7Encoding Represents a UTF-7 encoding of Unicode characters.

UTF8Encoding Represents a UTF-8 encoding of Unicode characters.

See Also
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic

2014 Microsoft. All rights reserved.


Troubleshooting: Reading from and Writing to Text Files
(Visual Basic)
Visual Studio 2012

This topic discusses common problems encountered when working with text files and suggests an approach to each.

Common Problems
The most common issues encountered when working with text files include security exceptions, file encodings, or invalid paths.

Security Exceptions
A SecurityException is thrown when a security error occurs. This is often a result of the user lacking necessary permissions, which may be solved by adding
permissions or working with files in isolated storage. For more information, see Troubleshooting Exceptions: System.Security.SecurityException.

File Encodings
File encodings, also known as character encodings, specify how to represent characters when text processing. Unexpected characters in a text file may result from
incorrect encoding. For most files, one encoding may be preferable over another in terms of which language characters it can or cannot handle, although Unicode is
usually preferred. For more information, see File Encodings (Visual Basic) and Encoding.

Incorrect Paths
When parsing file paths, particularly relative paths, it is easy to supply the wrong data. Many problems can be corrected by making sure you are supplying the correct
path. For more information, see How to: Parse File Paths in Visual Basic.

See Also
Reference
FileSystem
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic

2014 Microsoft. All rights reserved.


Basics of .NET Framework File I/O and the File System (Visual
Basic)
Visual Studio 2012

Classes in the System.IO namespace are used to work with drives, files, and directories.

The System.IO namespace contains the File and Directory classes, which provide the .NET Framework functionality that manipulates files and directories. Because the
methods of these objects are static or shared members, you can use them directly without creating an instance of the class first. Associated with these classes are the
FileInfo and DirectoryInfo classes, which will be familiar to users of the My feature. To use these classes, you must fully qualify the names or import the appropriate
namespaces by including the Imports statement(s) at the beginning of the affected code. For more information, see Imports Statement (.NET Namespace and Type).

Note

Other topics in this section use the My.Computer.FileSystem object instead of System.IO classes to work with drives, files, and directories. The
My.Computer.FileSystem object is intended primarily for use in Visual Basic programs. System.IO classes are intended for use by any language that supports the .NET
Framework, including Visual Basic.

Definition of a Stream
The .NET Framework uses streams to support reading from and writing to files. You can think of a stream as a one-dimensional set of contiguous data, which has a
beginning and an end, and where the cursor indicates the current position in the stream.

Stream Operations
The data contained in the stream may come from memory, a file, or a TCP/IP socket. Streams have fundamental operations that can be applied to them:

Reading. You can read from a stream, transferring data from the stream into a data structure, such as a string or an array of bytes.

Writing. You can write to a stream, transferring data from a data source into the stream.

Seeking. You can query and modify your position in the stream.

For more information, see Composing Streams.

Types of Streams
In the .NET Framework, a stream is represented by the Stream class, which forms the abstract class for all other streams. You cannot directly create an instance of the
Stream class, but must use one of the classes it implements.

There are many types of streams, but for the purposes of working with file input/output (I/O), the most important types are the FileStream class, which provides a way to
read from and write to files, and the IsolatedStorageFileStream class, which provides a way to create files and directories in isolated storage. Other streams that can be
used when working with file I/O include:

BufferedStream

CryptoStream

MemoryStream

NetworkStream .

The following table lists tasks commonly accomplished with a stream:

To See

Read and write to a data file How to: Read and Write to a Newly Created Data File

Read text from a file How to: Read Text from a File
Write text to a file How to: Write Text to a File

Read characters from a string How to: Read Characters from a String

Write characters to a string How to: Write Characters to a String

Encrypt data Encrypting Data

Decrypt data Decrypting Data

File Access and Attributes


You can control how files are created, opened, and shared with the FileAccess, FileMode, and FileShare enumerations, which contain the flags used by the constructors of
the FileStream class. For example, when you open or create a new FileStream, the FileMode enumeration allows you to specify whether the file is opened for appending,
whether a new file is created if the specified file does not exist, whether the file is overwritten, and so forth.

The FileAttributes enumeration enables the gathering of file-specific information. The FileAttributes enumeration returns the file's stored attributes, such as whether it is
compressed, encrypted, hidden, read-only, an archive, a directory, a system file, or a temporary file.

The following table lists tasks involving file access and file attributes:

To See

Open and append text to a log file How to: Open and Append to a Log File

Determine the attributes of a file FileAttributes

File Permissions
Controlling access to files and directories can be done with the FileIOPermission class. This may be particularly important for developers working with Web Forms, which
by default run within the context of a special local user account named ASPNET, which is created as part of the ASP.NET and .NET Framework installations. When such an
application requests access to a resource, the ASPNET user account has limited permissions, which may prevent the user from performing actions such as writing to a
file from a Web application. For more information, see Security Permissions, and the FileIOPermission.

Isolated File Storage


Isolated storage is an attempt to solve problems created when working with files where the user or code may lack necessary permissions. Isolated storage assigns each
user a data compartment, which can hold one or more stores. Stores can be isolated from each other by user and by assembly. Only the user and assembly that created
a store have access to it. A store acts as a complete virtual file systemwithin one store you can create and manipulate directories and files.

The following table lists tasks commonly associated with isolated file storage.

To See

Create an isolated store How to: Obtain Stores for Isolated Storage

Enumerate isolated stores How to: Enumerate Stores for Isolated Storage

Delete an isolated store How to: Delete Stores in Isolated Storage

Create a file or directory in isolated storage How to: Create Files and Directories in Isolated Storage

Find a file in isolated storage How to: Find Existing Files and Directories in Isolated Storage

Read from or write to a file in insolated storage How to: Read and Write to Files in Isolated Storage

Delete a file or directory in isolated storage How to: Delete Files and Directories in Isolated Storage

File Events
The FileSystemWatcher component allows you to watch for changes in files and directories on your system or on any computer to which you have network access. For
example, if a file is modified, you might want to send a user an alert that the change has taken place. When changes occur, one or more events are raised, stored in a
buffer, and handed to the FileSystemWatcher component for processing.

See Also
Concepts
Composing Streams
Asynchronous File I/O
Classes Used in .NET Framework File I/O and the File System (Visual Basic)
Other Resources
File and Stream I/O

2014 Microsoft. All rights reserved.


Classes Used in .NET Framework File I/O and the File System
(Visual Basic)
Visual Studio 2012

The following tables list the classes commonly used for .NET Framework file I/O, categorized into file I/O classes, classes used for creating streams, and classes used to
read and write to streams.

To enter the .NET Framework 2.0 documentation and find a more comprehensive listing, see .NET Framework Class Library Overview.

Basic I/O Classes for Files, Drives, and Directories


The following table lists and describes the main classes used for file I/O.

Class Description

Directory Provides static methods for creating, moving, and enumerating through directories and subdirectories.

DirectoryInfo Provides instance methods for creating, moving, and enumerating through directories and subdirectories.

DriveInfo Provides instance methods for creating, moving, and enumerating through drives.

File Provides static methods for creating, copying, deleting, moving, and opening files, and aids in the creation of a FileStream.

FileAccess Defines constants for read, write, or read/write access to a file.

FileAttributes Provides attributes for files and directories such as Archive, Hidden, and ReadOnly.

FileInfo Provides static methods for creating, copying, deleting, moving, and opening files, and aids in the creation of a FileStream.

FileMode Controls how a file is opened. This parameter is specified in many of the constructors for FileStream and IsolatedStorageFileStream, and for the
Open methods of File and FileInfo.

FileShare Defines constants for controlling the type of access other file streams can have to the same file.

Path Provides methods and properties for processing directory strings.

FileIOPermission Controls the access of files and folders by defining Read, Write, Append and PathDiscovery permissions.

Classes Used to Create Streams


The following table lists and describes the main classes used to create streams.

Class Description

BufferedStream Adds a buffering layer to read and write operations on another stream.

FileStream Supports random access to files through its Seek method. FileStream opens files synchronously by default but also supports asynchronous
operation.

MemoryStream Creates a stream whose backing store is memory, rather than a file.

NetworkStream Provides the underlying stream of data for network access.

CryptoStream Defines a stream that links data streams to cryptographic transformations.

Classes Used to Read from and Write to Streams


The following table shows the specific classes used for reading from and writing to files with streams.

Class Description

BinaryReader Reads encoded strings and primitive data types from a FileStream.

BinaryWriter Writes encoded strings and primitive data types to a FileStream.

StreamReader Reads characters from a FileStream, using CurrentEncoding to convert characters to and from bytes. StreamReader has a constructor that attempts
to ascertain the correct CurrentEncoding for a given stream, based on the presence of a CurrentEncoding-specific preamble, such as a byte order
mark.
StreamWriter Writes characters to a FileStream, using Encoding to convert characters to bytes.

StringReader Reads characters from a String. Output can be either a stream in any encoding or a String.

StringWriter Writes characters to a String. Output can be either a stream in any encoding or a String.

See Also
Concepts
Composing Streams
Asynchronous File I/O
Basics of .NET Framework File I/O and the File System (Visual Basic)
Other Resources
File and Stream I/O

2014 Microsoft. All rights reserved.


Walkthrough: Manipulating Files by Using .NET Framework
Methods (Visual Basic)
Visual Studio 2012

This walkthrough demonstrates how to open and read a file using the StreamReader class, check to see if a file is being accessed, search for a string within a file read with
an instance of the StreamReader class, and write to a file using the StreamWriter class.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that
you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Creating the Application


Start Visual Studio and begin the project by creating a form that the user can use to write to the designated file.

To create the project

1. On the File menu, select New Project.

2. In the New Project pane, click Windows Application.

3. In the Name box type MyDiary and click OK.

Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.

4. Add the controls in the following table to the form and set the corresponding values for their properties.

Object Properties Value

Button Name Submit


Text Submit Entry

Button Name Clear


Text Clear Entry

TextBox Name Entry


Text Please enter something.
Multiline False

Writing to the File


To add the ability to write to a file via the application, use the StreamWriter class. StreamWriter is designed for character output in a particular encoding, whereas the
Stream class is designed for byte input and output. Use StreamWriter for writing lines of information to a standard text file. For more information on the StreamWriter
class, see StreamWriter.

To add writing functionality

1. From the View menu, choose Code to open the Code Editor.

2. Because the application references the System.IO namespace, add the following statements at the very beginning of your code, before the class declaration for
the form, which begins Public Class Form1.

VB

Imports System
Imports System.IO

Before writing to the file, you must create an instance of a StreamWriter class.

3. From the View menu, choose Designer to return to the Windows Forms Designer. Double-click the Submit button to create a Click event handler for the button,
and then add the following code.

VB

Dim fw As StreamWriter

Note

The Visual Studio Integrated Development Environment (IDE) will return to the Code Editor and position the insertion point within the event handler where you should
add the code.
1. To write to the file, use the Write method of the StreamWriter class. Add the following code directly after Dim fw As StreamWriter. You do not need to worry
that an exception will be thrown if the file is not found, because it will be created if it does not already exist.

VB

Dim ReadString As String


Try
'Pass the file path and name to the StreamWriter constructor.
'Indicate that Append is True, so file will not be overwritten.
fw = New StreamWriter("C:\MyDiary.txt", True)
ReadString = Entry.Text
fw.WriteLine(ReadString)
Finally
'Close the file.
fw.Close()
End Try

2. Make sure that the user cannot submit a blank entry by adding the following code directly after Dim ReadString As String.

VB

If (Entry.Text = "" Or Entry.Text = "Please enter something.") Then


Entry.Text = "Please enter something."
Return
End If

3. Because this is a diary, the user will want to assign a date to each entry. Insert the following code after fw = New StreamWriter("C:\MyDiary.txt", True) to
set the variable Today to the current date.

VB

Dim Today As DateTime


Today = Now
fw.Write(CStr(Today))
fw.Write(ControlChars.CrLf)

4. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.

VB

Entry.Text = ""

Adding Display Features to the Diary


In this section, you add a feature that displays the latest entry in the DisplayEntry TextBox. You can also add a ComboBox that displays various entries and from which
a user can select an entry to display in the DisplayEntry TextBox. An instance of the StreamReader class reads from MyDiary.txt. Like the StreamWriter class,
StreamReader is intended for use with text files.

For this section of the walkthrough, add the controls in the following table to the form and set the corresponding values for their properties.

Control Properties Values

TextBox Name DisplayEntry


Visible False
Size 120,60
Multiline True

Button Name Display


Text Display

Button Name GetEntries


Text Get Entries

ComboBox Name PickEntries


Text Select an Entry
Enabled False

To populate the combo box

1. The PickEntries ComboBox is used to display the dates on which a user submits each entry, so the user can select an entry from a specific date. Create a Click
event handler to the GetEntries button and add the following code.

VB

Dim fr As StreamReader = Nothing


Dim FileString As String
FileString = ""
Try
fr = New System.IO.StreamReader("C:\MyDiary.txt")
PickEntries.Items.Clear()
PickEntries.Enabled = True
Do
FileString = fr.ReadLine
If IsDate(FileString) Then
PickEntries.Items.Add(FileString)
End If
Loop Until (FileString Is Nothing)
Finally
If fr IsNot Nothing Then
fr.Close()
End If
End Try
PickEntries.Enabled = True

2. To test your code, press F5 to compile the application, and then click Get Entries. Click the drop-down arrow in the ComboBox to display the entry dates.

To choose and display individual entries

1. Create a Click event handler for the Display button and add the following code.

VB

Dim fr As StreamReader
Dim ReadString As String
'Make sure ReadString begins empty.
ReadString = ""
Dim FileString As String
fr = New StreamReader("C:\MyDiary.txt")
'If no entry has been selected, show the whole file.
If PickEntries.Enabled = False Or PickEntries.SelectedText Is Nothing Then
Do
'Read a line from the file into FileString.
FileString = fr.ReadLine
'add it to ReadString
ReadString = ReadString & ControlChars.CrLf & FileString
Loop Until (FileString = Nothing)
Else
'An entry has been selected, find the line that matches.
Do

FileString = fr.ReadLine
Loop Until FileString = CStr(PickEntries.SelectedItem)
FileString = CStr(PickEntries.SelectedItem) & ControlChars.CrLf
ReadString = FileString & fr.ReadLine

'Read from the file until EOF or another Date is found.


Do Until ((fr.Peek < 0) Or (IsDate(fr.ReadLine)))
ReadString = ReadString & fr.ReadLine
Loop
End If
fr.Close()
DisplayEntry.Visible = True
DisplayEntry.Text = ReadString

2. To test your code, press F5 to compile the application, and then submit an entry. Click Get Entries, select an entry from the ComboBox, and then click Display.
The contents of the selected entry appear in the DisplayEntry TextBox.

Enabling Users to Delete or Modify Entries


Finally, you can include additional functionality enables users to delete or modify an entry by using DeleteEntry and EditEntry buttons. Both buttons remain disabled
unless an entry is displayed.

Add the controls in the following table to the form and set the corresponding values for their properties.

Control Properties Values

Button Name DeleteEntry


Text Delete Entry
Enabled False

Button Name EditEntry


Text Edit Entry
Enabled False

Button Name SubmitEdit


Text Submit Edit
Enabled False
To enable deletion and modification of entries

1. Add the following code to the Display button's Click event, after DisplayEntry.Text = ReadString.

VB

DeleteEntry.enabled = True

2. Create a Click event handler for the DeleteEntry button and add the following code.

VB

Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
Dim ConfirmDelete As MsgBoxResult
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
' Read through the textfile
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, "")
fr.Close()
' Check to make sure the user wishes to delete the entry
ConfirmDelete = MsgBox("Do you really wish to delete this entry?",
MsgBoxStyle.OKCancel)
If ConfirmDelete = MsgBoxResult.OK Then
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
' Reset controls on the form
DisplayEntry.Text = ""
PickEntries.Text = ""
PickEntries.Items.Clear()
PickEntries.Enabled = False
DeleteEntry.Enabled = False
End If

3. When a user displays an entry, the EditEntry button becomes enabled. Add the following code to the Click event of the Display button after
DisplayEntry.Text = ReadString.

VB

EditEntry.Enabled = True

4. Create a Click event handler for the EditEntry button and add the following code.

VB

Entry.Text = DisplayEntry.Text
SubmitEdit.Enabled = True

5. Create a Click event handler for the SubmitEdit button and add the following code

VB

Dim fr As StreamReader
Dim ReadString As String
Dim WriteString As String
If Entry.Text = "" Then
MsgBox("Use Delete to Delete an Entry")
Return
End If
fr = New StreamReader("C:\MyDiary.txt")
ReadString = fr.ReadLine
Do Until (fr.Peek < 0)
ReadString = ReadString & vbCrLf & fr.ReadLine
Loop
WriteString = Replace(ReadString, DisplayEntry.Text, Entry.Text)
fr.Close()
File.Delete("C:\MyDiary.txt")
Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
fw.WriteLine(WriteString)
fw.Close()
DisplayEntry.Text = Entry.Text
Entry.Text = ""
EditEntry.Enabled = False
SubmitEdit.Enabled = False

To test your code, press F5 to compile the application. Click Get Entries, select an entry, and then click Display. The entry appears in the DisplayEntry TextBox. Click
Edit Entry. The entry appears in the Entry TextBox. Edit the entry in the Entry TextBox and click Submit Edit. Open the MyDiary.txt file to confirm your correction.
Now select an entry and click Delete Entry. When the MessageBox requests confirmation, click OK. Close the application and open MyDiary.txt to confirm the deletion.

See Also
Reference
StreamReader
StreamWriter
Other Resources
Visual Basic Language Walkthroughs

2014 Microsoft. All rights reserved.


Walkthrough: Manipulating Files and Directories in Visual Basic
Visual Studio 2012

This walkthrough provides an introduction to the fundamentals of file I/O in Visual Basic. It describes how to create a small application that lists and examines text files in a
directory. For each selected text file, the application provides file attributes and the first line of content. There is an option to write information to a log file.

This walkthrough uses members of the My.Computer.FileSystem Object, which are available in Visual Basic. See FileSystem for more information. At the end of the
walkthrough, an equivalent example is provided that uses classes from the System.IO namespace.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that
you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To create the project

1. On the File menu, click New Project.

The New Project dialog box appears.

2. In the Installed Templates pane, expand Visual Basic, and then click Windows. In the Templates pane in the middle, click Windows Forms Application.

3. In the Name box, type FileExplorer to set the project name, and then click OK.

Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.

4. Add the controls in the following table to the form, and set the corresponding values for their properties.

Control Property Value

ListBox Name filesListBox

Button Name browseButton


Text Browse

Button Name examineButton


Text Examine

CheckBox Name saveCheckBox


Text Save Results

FolderBrowserDialog Name FolderBrowserDialog1

To select a folder, and list files in a folder

1. Create a Click event handler for browseButton by double-clicking the control on the form. The Code Editor opens.

2. Add the following code to the Click event handler.

VB

If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then


' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If

The FolderBrowserDialog1.ShowDialog call opens the Browse For Folder dialog box. After the user clicks OK, the SelectedPath property is sent as an argument
to the ListFiles method, which is added in the next step.

3. Add the following ListFiles method.

VB

Private Sub ListFiles(ByVal folderPath As String)


filesListBox.Items.Clear()

Dim fileNames = My.Computer.FileSystem.GetFiles(


folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

For Each fileName As String In fileNames


filesListBox.Items.Add(fileName)
Next
End Sub

This code first clears the ListBox.

The GetFiles method then retrieves a collection of strings, one for each file in the directory. The GetFiles method accepts a search pattern argument to retrieve files
that match a particular pattern. In this example, only files that have the extension .txt are returned.

The strings that are returned by the GetFiles method are then added to the ListBox.

4. Run the application. Click the Browse button. In the Browse For Folder dialog box, browse to a folder that contains .txt files, and then select the folder and click OK.

The ListBox contains a list of .txt files in the selected folder.

5. Stop running the application.

To obtain attributes of a file, and content from a text file

1. Create a Click event handler for examineButton by double-clicking the control on the form.

2. Add the following code to the Click event handler.

VB

If filesListBox.SelectedItem Is Nothing Then


MessageBox.Show("Please select a file.")
Exit Sub
End If

' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString

' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If

' Obtain file information in a string.


Dim fileInfoText As String = GetTextForOutput(filePath)

' Show the file information.


MessageBox.Show(fileInfoText)

The code verifies that an item is selected in the ListBox. It then obtains the file path entry from the ListBox. The FileExists method is used to check whether the file
still exists.

The file path is sent as an argument to the GetTextForOutput method, which is added in the next step. This method returns a string that contains file information.
The file information appears in a MessageBox.

3. Add the following GetTextForOutput method.

VB

Private Function GetTextForOutput(ByVal filePath As String) As String


' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If

' Create a new StringBuilder, which is used


' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()

' Obtain file information.


Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

' Add file attributes.


sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)

' Open the text file.


Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)

' Add the first line from the file.


If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()

Return sb.ToString
End Function

The code uses the GetFileInfo method to obtain file parameters. The file parameters are added to a StringBuilder.
The OpenTextFileReader method reads the file contents into a StreamReader. The first line of the contents is obtained from the StreamReader and is added to the
StringBuilder.

4. Run the application. Click Browse, and browse to a folder that contains .txt files. Click OK.

Select a file in the ListBox, and then click Examine. A MessageBox shows the file information.

5. Stop running the application.

To add a log entry

1. Add the following code to the end of the examineButton_Click event handler.

VB

If saveCheckBox.Checked = True Then


' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

Dim logText As String = "Logged: " & Date.Now.ToString &


vbCrLf & fileInfoText & vbCrLf & vbCrLf

' Append text to the log file.


My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If

The code sets the log file path to put the log file in the same directory as that of the selected file. The text of the log entry is set to the current date and time
followed by the file information.

The WriteAllText method, with the append argument set to True, is used to create the log entry.

2. Run the application. Browse to a text file, select it in the ListBox, select the Save Results check box, and then click Examine. Verify that the log entry is written to the
log.txt file.

3. Stop running the application.

To use the current directory

1. Create an event handler for Form1_Load by double-clicking the form.

2. Add the following code to the event handler.

VB

' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

This code sets the default directory of the folder browser to the current directory.

3. Run the application. When you click Browse the first time, the Browse For Folder dialog box opens to the current directory.

4. Stop running the application.

To selectively enable controls

1. Add the following SetEnabled method.

VB

Private Sub SetEnabled()


Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)

examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub

The SetEnabled method enables or disables controls depending on whether an item is selected in the ListBox.

2. Create a SelectedIndexChanged event handler for filesListBox by double-clicking the ListBox control on the form.

3. Add a call to SetEnabled in the new filesListBox_SelectedIndexChanged event handler.

4. Add a call to SetEnabled at the end of the browseButton_Click event handler.

5. Add a call to SetEnabled at the end of the Form1_Load event handler.

6. Run the application. The Save Results check box and the Examine button are disabled if an item is not selected in the ListBox.
Full example using My.Computer.FileSystem
Following is the complete example.

VB

' This example uses members of the My.Computer.FileSystem


' object, which are available in Visual Basic.

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


' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory

SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click


If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If
SetEnabled()
End Sub

Private Sub ListFiles(ByVal folderPath As String)


filesListBox.Items.Clear()

Dim fileNames = My.Computer.FileSystem.GetFiles(


folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")

For Each fileName As String In fileNames


filesListBox.Items.Add(fileName)
Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click


If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If

' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString

' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If

' Obtain file information in a string.


Dim fileInfoText As String = GetTextForOutput(filePath)

' Show the file information.


MessageBox.Show(fileInfoText)

If saveCheckBox.Checked = True Then


' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")

Dim logText As String = "Logged: " & Date.Now.ToString &


vbCrLf & fileInfoText & vbCrLf & vbCrLf

' Append text to the log file.


My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String


' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If

' Create a new StringBuilder, which is used


' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()

' Obtain file information.


Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)

' Add file attributes.


sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)

' Open the text file.


Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)

' Add the first line from the file.


If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()

Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChang


SetEnabled()
End Sub

Private Sub SetEnabled()


Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)

examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub

Full example using System.IO


The following equivalent example uses classes from the System.IO namespace instead of using My.Computer.FileSystem objects.

VB

' This example uses classes from the System.IO namespace.

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


' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath =
System.IO.Directory.GetCurrentDirectory()

SetEnabled()
End Sub

Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click


If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
SetEnabled()
End If
End Sub

Private Sub ListFiles(ByVal folderPath As String)


filesListBox.Items.Clear()

Dim fileNames As String() =


System.IO.Directory.GetFiles(folderPath,
"*.txt", System.IO.SearchOption.TopDirectoryOnly)

For Each fileName As String In fileNames


filesListBox.Items.Add(fileName)
Next
End Sub

Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click


If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If

' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString

' Verify that the file was not removed since the
' Browse button was clicked.
If System.IO.File.Exists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If

' Obtain file information in a string.


Dim fileInfoText As String = GetTextForOutput(filePath)

' Show the file information.


MessageBox.Show(fileInfoText)

If saveCheckBox.Checked = True Then


' Place the log file in the same folder as the examined file.
Dim logFolder As String =
System.IO.Path.GetDirectoryName(filePath)
Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")

' Append text to the log file.


Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf

System.IO.File.AppendAllText(logFilePath, logText)
End If
End Sub

Private Function GetTextForOutput(ByVal filePath As String) As String


' Verify that the file exists.
If System.IO.File.Exists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If

' Create a new StringBuilder, which is used


' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()

' Obtain file information.


Dim thisFile As New System.IO.FileInfo(filePath)

' Add file attributes.


sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)

' Open the text file.


Dim sr As System.IO.StreamReader =
System.IO.File.OpenText(filePath)

' Add the first line from the file.


If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()

Return sb.ToString
End Function

Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged


SetEnabled()
End Sub

Private Sub SetEnabled()


Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)

examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub

See Also
Tasks
Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)
Reference
System.IO
FileSystem
CurrentDirectory

2014 Microsoft. All rights reserved.


Reading from Files in Visual Basic
Visual Studio 2012

This section explains how to perform tasks that are associated with reading from files.

In This Section
How to: Read From Text Files in Visual Basic
Demonstrates how to read from a text file.

How to: Read From Comma-Delimited Text Files in Visual Basic


Demonstrates how to read from a delimited text file.

How to: Read From Fixed-width Text Files in Visual Basic


Demonstrates how to read from a fixed-width text file.

How to: Read From Text Files with Multiple Formats in Visual Basic
Demonstrates how to read from a text file with multiple formats.

How to: Read From Binary Files in Visual Basic


Demonstrates how to read from a binary file.

How to: Read Text from Files with a StreamReader (Visual Basic)
Demonstrates how to use a StreamReader to read from a file.

Reference
FileSystem
Describes the My.Computer.FileSystem object and its members.

ReadAllText
Describes the ReadAllText method.

ReadAllBytes
Describes the ReadAllBytes method.

OpenTextFieldParser
Describes the OpenTextFieldParser method.

OpenTextFileReader
Describes the OpenTextFileReader method.

Related Sections
Storing Data to and Reading from the Clipboard (Visual Basic)
Explains how to perform tasks that are associated with My.Computer.Clipboard, such as reading data from or writing data to the Clipboard.

Parsing Text Files with the TextFieldParser Object (Visual Basic)


Provides an overview of reading text files with the TextFieldParser object.

Walkthrough: Manipulating Files and Directories in Visual Basic


Demonstrates how to use the My feature with files and directories.

Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)


Demonstrates how to use .NET Framework methods with files and directories.

2014 Microsoft. All rights reserved.


How to: Read From Text Files in Visual Basic
Visual Studio 2012

The ReadAllText method of the My.Computer.FileSystem object allows you to read from a text file. The file encoding can be specified if the contents of the file use an
encoding such as ASCII or UTF-8.

If you are reading from a file with extended characters, you will need to specify the file encoding.

Note

To read a file a single line of text at a time, use the OpenTextFileReader method of the My.Computer.FileSystem object. The OpenTextFileReader method returns a
StreamReader object. You can use the ReadLine method of the StreamReader object to read a file one line at a time. You can test for the end of the file using the
EndOfStream method of the StreamReader object.

To read from a text file

Use the ReadAllText method of the My.Computer.FileSystem object to read the contents of a text file into a string, supplying the path. The following example
reads the contents of test.txt into a string and then displays it in a message box.

VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
MsgBox(fileReader)

To read from a text file that is encoded

Use the ReadAllText method of the My.Computer.FileSytem object to read the contents of a text file into a string, supplying the path and file encoding type. The
following example reads the contents of the UTF32 file test.txt into a string and then displays it in a message box.

VB

Dim fileReader As String


fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt",
System.Text.Encoding.UTF32)
MsgBox(fileReader)

Robust Programming
The following conditions may cause an exception:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

There is not enough memory to write the string to buffer (OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Walkthrough: Manipulating Files and Directories in Visual Basic
Reference
FileSystem
ReadAllText
Concepts
File Encodings (Visual Basic)
Other Resources
Reading from Files in Visual Basic

2014 Microsoft. All rights reserved.


How to: Read From Comma-Delimited Text Files in Visual Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. The TextFieldType property defines whether it is a delimited
file or one with fixed-width fields of text.

To parse a comma delimited text file

1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")

2. Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the delimiter as ",".

VB

MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")

3. Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops through the file, displaying each field in
turn and reporting any fields that are formatted incorrectly.

VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.

VB

End While
End Using

Example
This example reads from the file test.txt.

VB

Using MyReader As New Microsoft.VisualBasic.


FileIO.TextFieldParser(
"C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Fixed-width Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Fixed-width Text Files in Visual Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs.

The TextFieldType property defines whether the parsed file is a delimited file or one that has fixed-width fields of text. In a fixed-width text file, the field at the end can
have a variable width. To specify that the field at the end has a variable width, define it to have a width less than or equal to zero.

To parse a fixed-width text file

1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file test.log.

VB

Using Reader As New Microsoft.VisualBasic.


FileIO.TextFieldParser("C:\TestFolder\test.log")

2. Define the TextFieldType property as FixedWidth, defining the width and format. The following code defines the columns of text; the first is 5 characters wide, the
second 10, the third 11, and the fourth is of variable width.

VB

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)

3. Loop through the fields in the file. If any lines are corrupted, report an error and continue parsing.

VB

Dim currentRow As String()


While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try

4. Close the While and Using blocks with End While and End Using.

VB

End While
End Using

Example
This example reads from the file test.log.

VB

Using Reader As New Microsoft.VisualBasic.FileIO.


TextFieldParser("C:\TestFolder\test.log")

Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(5, 10, 11, -1)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Text Files with Multiple Formats in Visual Basic
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
Reference
TextFieldParser
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Text Files with Multiple Formats in Visual
Basic
Visual Studio 2012

The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. You can process a file with multiple formats by using the
PeekChars method to determine the format of each line as you parse through the file.

To parse a text file with multiple formats

1. Add a text file named testfile.txt to your project. Add the following content to the text file.

Err 1001 Cannot access resource.


Err 2014 Resource not found.
Acc 10/03/2009User1 Administrator.
Err 0323 Warning: Invalid access attempt.
Acc 10/03/2009User2 Standard user.
Acc 10/04/2009User2 Standard user.

2. Define the expected format and the format used when an error is reported. The last entry in each array is -1, therefore the last field is assumed to be of variable
width. This occurs when the last entry in the array is less than or equal to 0.

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}

3. Create a new TextFieldParser object, defining the width and format.

VB

Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")


MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat

4. Loop through the rows, testing for format before reading.

VB

Dim currentRow As String()


While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()

5. Write errors to the console.

VB

Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid.")
End Try
End While
End Using

Example
Following is the complete example that reads from the file testfile.txt.

VB

Dim stdFormat As Integer() = {5, 10, 11, -1}


Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = stdFormat
Dim currentRow As String()
While Not MyReader.EndOfData
Try
Dim rowType = MyReader.PeekChars(3)
If String.Compare(rowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(errorFormat)
Else
' Otherwise parse the fields normally
MyReader.SetFieldWidths(stdFormat)
End If
currentRow = MyReader.ReadFields
For Each newString In currentRow
Console.Write(newString & "|")
Next
Console.WriteLine()
Catch ex As FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
Console.ReadLine()

Robust Programming
The following conditions may cause an exception:

A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine
property is assigned to the text contained in the line.

The specified file does not exist (FileNotFoundException).

A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).

The path is too long (PathTooLongException).

The user does not have sufficient permissions to access the file (UnauthorizedAccessException).

See Also
Tasks
How to: Read From Comma-Delimited Text Files in Visual Basic
How to: Read From Fixed-width Text Files in Visual Basic
Reference
TextFieldParser
PeekChars
MalformedLineException
WriteAllText
EndOfData
TextFieldType
Concepts
Parsing Text Files with the TextFieldParser Object (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read From Binary Files in Visual Basic
Visual Studio 2012

The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.

To read from a binary file

Use the ReadAllBytes method, which returns the contents of a file as a byte array. This example reads from the file C:/Documents and
Settings/selfportrait.jpg.

VB

Dim bytes = My.Computer.FileSystem.ReadAllBytes(


"C:/Documents and Settings/selfportrait.jpg")
PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))

For large binary files, you can use the Read method of the FileStream object to read from the file only a specified amount at a time. You can then limit how much of
the file is loaded into memory for each read operation. The following code example copies a file and allows the caller to specify how much of the file is read into
memory per read operation.

VB

' This method does not trap for exceptions. If an exception is


' encountered opening the file to be copied or writing to the
' destination location, then the exception will be thrown to
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
ByVal copyPath As String,
ByVal bufferSize As Integer,
ByVal overwrite As Boolean)

Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then


My.Computer.FileSystem.DeleteFile(copyPath)
End If

' Adjust array length for VB array declaration.


Dim bytes = New Byte(bufferSize - 1) {}

While inputFile.Read(bytes, 0, bufferSize) > 0


My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
End While

inputFile.Close()
End Sub

Robust Programming
The following conditions may cause an exception to be thrown:

The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path
(ArgumentException).

The path is not valid because it is Nothing (ArgumentNullException).

The file does not exist (FileNotFoundException).

The file is in use by another process, or an I/O error occurs (IOException).

The path exceeds the system-defined maximum length (PathTooLongException).

A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).

There is not enough memory to write the string to buffer (OutOfMemoryException).

The user lacks necessary permissions to view the path (SecurityException).

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

See Also
Tasks
How to: Read From Text Files with Multiple Formats in Visual Basic
Reference
ReadAllBytes
WriteAllBytes
Other Resources
Reading from Files in Visual Basic
Storing Data to and Reading from the Clipboard (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Read Text from Files with a StreamReader (Visual
Basic)
Visual Studio 2012

The My.Computer.FileSystem object provides methods to open a TextReader and a TextWriter. These methods, OpenTextFileWriter and OpenTextFileReader, are
advanced methods that do not appear in IntelliSense unless you select the All tab.

To read a line from a file with a text reader

Use the OpenTextFileReader method to open the TextReader, specifying the file. This example opens the file named testfile.txt, reads a line from it, and
displays the line in a message box.

VB

Dim fileReader As System.IO.StreamReader


fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)

Robust Programming
The file that is read must be a text file.

Do not make decisions about the contents of the file based on the name of the file. For example, the file Form1.vb may not be a Visual Basic source file.

Verify all inputs before using the data in your application. The contents of the file may not be what is expected, and methods to read from the file may fail.

Security
To read from a file, your assembly requires a privilege level granted by the FileIOPermission class. If you are running in a partial-trust context, the code might throw an
exception due to insufficient privileges. For more information, see Code Access Security Basics. The user also needs access to the file. For more information, see ACL
Technology Overview.

See Also
Reference
FileSystem
OpenFileDialog
OpenTextFileWriter
OpenTextFileReader
Other Resources
SaveFileDialog Component (Windows Forms)
Reading from Files in Visual Basic

2014 Microsoft. All rights reserved.


Printing and Reporting (Visual Basic)
Visual Studio 2012

Visual Basic offers several options for printing and reporting. The following topics provide overviews and links to the relevant documentation related to printing and
reporting.

In This Section
PrintForm Component (Visual Basic)
Provides an overview of the PrintForm component that enables printing the contents of a form.

How to: Print a Scrollable Form (Visual Basic)


Explains how to print a scrollable form by using the PrintForm component.

How to: Print Client and Non-Client Areas of a Form (Visual Basic)
Explains how to print both the client and non-client areas of a form by using the PrintForm component.

How to: Print the Client Area of a Form (Visual Basic)


Explains how to print the client area of a form by using the PrintForm component.

How to: Print a Form by Using the PrintForm Component (Visual Basic)
Explains how to print a basic form by using the PrintForm component.

Deploying Applications That Reference the PrintForm Component (Visual Basic)


Discusses how to deploy the PrintForm component together with an application.

Adding Printable Reports to Visual Studio Applications


Discusses options available for writing reports.

2014 Microsoft. All rights reserved.


PrintForm Component (Visual Basic)
Visual Studio 2012

The PrintForm component for Visual Basic enables you to print an image of a Windows Form at run time. Its behavior replaces that of the PrintForm method in earlier
versions of Visual Basic.

PrintForm Component Overview


A common scenario for Windows Forms is to create a form that is formatted to resemble a paper form or a report, and then to print an image of the form. Although
you can use a PrintDocument component to do this, it would require a lot of code. The PrintForm component enables you to print an image of a form to a printer, to a
print preview window, or to a file without using a PrintDocument component.

The PrintForm component is located on the Visual Basic PowerPacks tab of the Toolbox. When it is dragged onto a form it appears in the component tray, the small
area under the bottom border of the form. When the component is selected, properties that define its behavior can be set in the Properties window. All of these
properties can also be set in code. You can also create an instance of the PrintForm component in code without adding the component at design time.

When you print a form, everything in the client area of the form is printed. This includes all controls and any text or graphics drawn on the form by graphics methods. By
default, the form's title bar, scroll bars, and border are not printed. Also by default, the PrintForm component prints only the visible part of the form. For example, if the
user resizes the form at run time, only the controls and graphics that are currently visible are printed.

The default printer used by the PrintForm component is determined by the operating system's Control Panel settings.

After printing is initiated, a standard PrintDocument printing dialog box is displayed. This dialog box enables users to cancel the print job.

Key Methods, Properties, and Events


The key method of the PrintForm component is the Print method, which prints an image of the form to a printer, print preview window, or file. There are two versions
of the Print method:

A basic version without parameters: Print()

An overloaded version with parameters that specify printing behavior: Print(printForm As Form, printFormOption As PrintOption)

The PrintOption parameter of the overloaded method determines the underlying implementation used to print the form, whether the form's title bar, scroll
bars, and border are printed, and whether scrollable parts of the form are printed.

The PrintAction property is a key property of the PrintForm component. This property determines whether the output is sent to a printer, displayed in a print preview
window, or saved as an Encapsulated PostScript file. If the PrintAction property is set to PrintToFile, the PrintFileName property specifies the path and file name.

The PrinterSettings property provides access to an underlying PrinterSettings object that enables you to specify such settings as the printer to use and the number of
copies to print. You can also query the printer's capabilities, such as color or duplex support. This property does not appear in the Properties window; it can be
accessed only from code.

The Form property is used to specify the form to print when you invoke the PrintForm component programmatically. If the component is added to a form at design
time, that form is the default.

Key events for the PrintForm component include the following:

BeginPrint event. Occurs when the Print method is called and before the first page of the document prints.

EndPrint event. Occurs after the last page is printed.

QueryPageSettings event. Occurs immediately before each page is printed.

Remarks
If a form contains text or graphics drawn by Graphics methods, use the basic Print (Print()) method to print it. Graphics may not render on some operating systems
when the overloaded Print method is used.

If the width of a form is wider than the width of the paper in the printer, the right side of the form might be cut off. When you design forms for printing, make sure
that the form fits on standard-sized paper.

Example
The following example shows a common use of the PrintForm component.

' Visual Basic.


Dim pf As New PrintForm
pf.Form = Me
pf.PrintAction = PrintToPrinter
pf.Print()

See Also
Tasks
How to: Print a Form by Using the PrintForm Component (Visual Basic)
How to: Print the Client Area of a Form (Visual Basic)
How to: Print Client and Non-Client Areas of a Form (Visual Basic)
How to: Print a Scrollable Form (Visual Basic)
Reference
Print
PrintAction

2014 Microsoft. All rights reserved.


How to: Print a Scrollable Form (Visual Basic)
Visual Studio 2012

The PrintForm component enables you to quickly print an image of a form without using a PrintDocument component. By default, only the currently visible part of the form
is printed; if a user has resized the form at run time, the image may not print as intended. The following procedure shows how to print the complete client area of a
scrollable form, even if the form has been resized.

To print the complete client area of a scrollable form

1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.

The PrintForm component will be added to the component tray.

2. In the Properties window, set the PrintAction property to PrintToPrinter.

3. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).

PrintForm1.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.Scrollable)

Note

On some operating systems, text or graphics drawn by Graphics methods may not print correctly. In this case, you will not be able to print with the Scrollable
parameter.

See Also
Tasks
How to: Print the Client Area of a Form (Visual Basic)
How to: Print Client and Non-Client Areas of a Form (Visual Basic)
Reference
PrintAction
Print
Concepts
PrintForm Component (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Print Client and Non-Client Areas of a Form (Visual
Basic)
Visual Studio 2012

The PrintForm component enables you to quickly print an image of a form exactly as it appears on screen without using a PrintDocument component. The following
procedure shows how to print a form, including both the client area and the non-client area. The non-client area includes the title bar, borders, and scroll bars.

To print both the client and the non-client areas of a form

1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.

The PrintForm component is added to the component tray.

2. In the Properties window, set the PrintAction property to PrintToPrinter.

3. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).

PrintForm1.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.FullWindow)

Note

On some operating systems, text or graphics drawn by Graphics methods may not print correctly. In this case, use the compatible printing method:
PrintForm1.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.CompatibleModeFullWindow).

See Also
Tasks
How to: Print a Scrollable Form (Visual Basic)
Reference
PrintAction
Print
Concepts
PrintForm Component (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Print the Client Area of a Form (Visual Basic)
Visual Studio 2012

The PrintForm component enables you to quickly print an image of a form without using a PrintDocument component. The following procedure shows how to print just the
client area of a form, without the title bar, borders, and scroll bars.

To print the client area of a form

1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.

The PrintForm component is added to the component tray.

2. In the Properties window, set the PrintAction property to PrintToPrinter.

3. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).

PrintForm1.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.ClientAreaOnly)

Note

On some operating systems, text or graphics drawn by Graphics methods may not print correctly. In this case, use the compatible printing method:
PrintForm1.Print(Me, PowerPacks.Printing.PrintForm.PrintOption CompatibleModeClientAreaOnly).

See Also
Tasks
How to: Print Client and Non-Client Areas of a Form (Visual Basic)
How to: Print a Scrollable Form (Visual Basic)
Reference
PrintAction
Print
Concepts
PrintForm Component (Visual Basic)

2014 Microsoft. All rights reserved.


How to: Print a Form by Using the PrintForm Component
(Visual Basic)
Visual Studio 2012

The PrintForm component enables you to quickly print an image of a form exactly as it appears on screen without using a PrintDocument component. The following
procedures show how to print a form to a printer, to a print preview window, and to an Encapsulated PostScript file.

To print a form to the default printer

1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.

The PrintForm component is added to the component tray.

2. In the Properties window, set the PrintAction property to PrintToPrinter.

3. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).

PrintForm1.Print()

To display a form in a print preview window

1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.

The PrintForm component is added to the component tray.

2. In the Properties window, set the PrintAction property to PrintToPreview.

3. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).

PrintForm1.Print()

To print a form to a file

1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.

The PrintForm component is added to the component tray.

2. In the Properties window, set the PrintAction property to PrintToFile.

3. Optionally, select the PrintFileName property and type the full path and file name for the destination file.

If you skip this step, the user will be prompted for a file name at run time.

4. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).

PrintForm1.Print()

See Also
Tasks
How to: Print the Client Area of a Form (Visual Basic)
How to: Print Client and Non-Client Areas of a Form (Visual Basic)
How to: Print a Scrollable Form (Visual Basic)
Reference
PrintAction
PrintFileName
Concepts
PrintForm Component (Visual Basic)

2014 Microsoft. All rights reserved.


Deploying Applications That Reference the PrintForm
Component (Visual Basic)
Visual Studio 2012

If you want to deploy an application that references the PrintForm component, the component must be installed on the destination computer.

Installing the PrintForm as a Prerequisite


To successfully deploy an application, you must also deploy all components that are referenced by the application. The process of installing prerequisite components is
known as bootstrapping.

When the PrintForm component is installed on your development computer, a Microsoft Visual Basic Power Packs bootstrapper package is added to the Visual Studio
bootstrapper directory. This package is then available when you follow the procedures for adding prerequisites for either ClickOnce or Windows Installer deployment.

By default, bootstrapped components are deployed from the same location as the installation package. Alternatively, you can choose to deploy the components from a
URL or file share location from which users can download them as necessary.

Note

To install bootstrapped components, the user might need administrative or similar user permissions on the computer. For ClickOnce applications, this means that the
user will need administrative permissions to install the application, regardless of the security level specified by the application. After the application is installed, the
user can run the application without administrative permissions.

During installation, users will be prompted to install the PrintForm component if it is not present on the destination computer.

As an alternative to bootstrapping, you can pre-deploy the PrintForm component by using an electronic software distribution system like Microsoft Systems
Management Server.

See Also
Tasks
How to: Install Prerequisites with a ClickOnce Application
Concepts
Choosing a Deployment Strategy
PrintForm Component (Visual Basic)

2014 Microsoft. All rights reserved.


Adding Printable Reports to Visual Studio Applications
Visual Studio 2012

Visual Studio supports a variety of reporting solutions to help you add rich data reporting to your Visual Basic applications. You can create and add reports using
ReportViewer controls, Crystal Reports, or SQL Server Reporting Services.

Note

SQL Server Reporting Services is part of SQL Server 2005 rather than Visual Studio. Reporting Services not installed on your system unless you have installed SQL Server
2005.

Overview of Microsoft Reporting Technology in Visual Basic Applications


Choose from the following approaches to use a Microsoft reporting technology in your application:

Add one or more instances of a ReportViewer control to a Visual Basic Windows application.

Integrate SQL Server Reporting Services programmatically by making calls to the Report Server Web service.

Use the ReportViewer control and Microsoft SQL Server 2005 Reporting Services together, using the control as a report viewer and a report server as a report
processor. (Note that you must use the SQL Server 2005 version of Reporting Services if you want to use a report server and the ReportViewer control together).

Using ReportViewer Controls


The easiest way to embed report functionality into a Visual Basic Windows application is to add the ReportViewer control to a form in your application. The control adds
report processing capabilities directly to your application and provides an integrated report designer so that you can build reports using data from any ADO.NET data
object. A full-featured API provides programmatic access to the control and reports so that you can configure run-time functionality.

ReportViewer provides built-in report processing and viewing capability in a single, freely distributable data control. Choose ReportViewer controls if you require the
following report functionality:

Report processing in the client application. A processed report appears in a view area provided by the control.

Data binding to ADO.NET data tables. You can create reports that consume DataTable instances supplied to the control. You can also bind directly to business
objects.

Redistributable controls that you can include in your application.

Runtime functionality such as page navigation, printing, searching, and export formats. A ReportViewer toolbar provides support for these operations.

To use the ReportViewer control, you can drag it from the Data section of the Visual Studio Toolbox onto a form in your Visual Basic Windows application.

Creating Reports in Visual Studio for ReportViewer Controls


To build a report that runs in ReportViewer, add a Report template to your project. Visual Studio creates a client report definition file (.rdlc), adds the file to your
project, and opens an integrated report designer in the Visual Studio workspace.

The Visual Studio Report Designer integrates with the Data Sources window. When you drag a field from the Data Sources window to the report, the Report Designer
copies metadata about the data source into the report definition file. This metadata is used by the ReportViewer control to automatically generate data-binding code.

The Visual Studio Report Designer does not include report preview functionality. To preview your report, run the application and preview the report embedded in it.

To add basic report functionality to your application

1. Drag a ReportViewer control from the Data tab of the Toolbox onto your form.
2. On the Project menu, choose Add New Item. In the Add New Item dialog box, select the Report icon and click Add.
The Report Designer opens in the development environment, and a report (.rdlc) file is added to the project.
3. Drag report items from the Toolbox on the report layout and arrange them as you want.
4. Drag fields from the Data Sources window to the report items in the report layout.

Using Reporting Services in Visual Basic Applications


Reporting Services is a server-based reporting technology that is included with SQL Server. Reporting Services includes additional features that are not found in the
ReportViewer controls. Choose Reporting Services if you require any of the following features:

Scale-out deployment and server-side report processing that provides improved performance for complex or long-running reports and for high-volume report
activity.
Integrated data and report processing, with support for custom report controls and rich rendering output formats.

Scheduled report processing so that you can specify exactly when reports are run.

Subscriber-based report distribution through e-mail or to file share locations.

Ad hoc reporting so that business users can create reports as needed.

Data-driven subscriptions that route customized report output to a dynamic list of recipients.

Custom extensions for data processing, report delivery, custom authentication, and report rendering.

The report server is implemented as Web service. Your application code must include calls to the Web service to access reports and other metadata. The Web service
provides complete programmatic access to a report server instance.

Because Reporting Services is a Web-based reporting technology, the default viewer shows reports that are rendered in HTML format. If you do not want to use HTML
as the default report presentation format, you will have to write a custom report viewer for your application.

Creating Reports in Visual Studio for Reporting Services


To build reports that run on a report server, you create report definition (.rdl) files in Visual Studio through the Business Intelligence Development Studio, which is
included with SQL Server 2005.

Note

You must have SQL Server 2005 installed in order to use SQL Server Reporting Services and the Business Intelligence Development Studio.

The Business Intelligence Development Studio adds project templates that are specific to SQL Server components. To create reports, you can choose from the Report
Server Project or Report Server Project Wizard templates. You can specify data source connections and queries to a variety of data source types, including SQL
Server, Oracle, Analysis Services, XML, and SQL Server Integration Services. A Data tab, Layout tab, and Preview tab allow you to define data, create a report layout,
and preview the report all in the same workspace.

Report definitions that you build for the control or the report server can be reused in either technology.

To create a report that runs on a report server

1. On the File menu, choose New.


The New Project dialog box opens.
2. In the Project types pane, click Business Intelligence Projects.
3. In the Templates pane, select Report Server Project or Report Server Project Wizard.

Using ReportViewer Controls and SQL Server Reporting Services Together


The ReportViewer controls and SQL Server 2005 Reporting Services can be used together in the same application.

The ReportViewer control provides a viewer that is used to display reports in your application.

Reporting Services provides the reports and performs all processing on a remote server.

The ReportViewer control can be configured to show reports that are stored and processed on a remote Reporting Services report server. This type of configuration is
called remote processing mode. In remote processing mode, the control requests a report that is stored on a remote report server. The report server performs all report
processing, data processing, and report rendering. A finished, rendered report is returned to the control and displayed in the view area.

Reports that run on a report server support additional export formats, have a different report parameterization implementation, use the data source types that are
supported by the report server, and are accessed through the role-based authorization model on the report server.

To use remote processing mode, specify the URL and path to a server report when configuring the ReportViewer control.

2014 Microsoft. All rights reserved.


Customizing Projects and Extending My with Visual Basic
Visual Studio 2012

You can customize project templates to provide additional My objects. This makes it easy for other developers to find and use your objects.

In This Section
Extending the My Namespace in Visual Basic
Describes how to add custom members and values to the My namespace in Visual Basic.

Packaging and Deploying Custom My Extensions (Visual Basic)


Describes how to publish custom My namespace extensions by using Visual Studio templates.

Extending the Visual Basic Application Model


Describes how to specify your own extensions to the application model by overriding members of the WindowsFormsApplicationBase class.

Customizing Which Objects are Available in My (Visual Basic)


Describes how to control which My objects are enabled by setting your project's _MYTYPE conditional-compilation constant.

Related Sections
Development with My (Visual Basic)
Describes which My objects are available in different project types by default.

Overview of the Visual Basic Application Model


Describes Visual Basic's model for controlling the behavior of Windows Forms applications.

How My Depends on Project Type (Visual Basic)


Describes which My objects are available in different project types by default.

Conditional Compilation in Visual Basic


Discusses how the compiler uses conditional-compilation to select particular sections of code to compile and exclude other sections.

ApplicationBase
Describes the My object that provides properties, methods, and events related to the current application.

See Also
Other Resources
Developing Applications with Visual Basic

2014 Microsoft. All rights reserved.


Extending the My Namespace in Visual Basic
Visual Studio 2012

The My namespace in Visual Basic exposes properties and methods that enable you to easily take advantage of the power of the .NET Framework. The My namespace
simplifies common programming problems, often reducing a difficult task to a single line of code. Additionally, the My namespace is fully extensible so that you can
customize the behavior of My and add new services to its hierarchy to adapt to specific application needs. This topic discusses both how to customize existing members of
the My namespace and how to add your own custom classes to the My namespace.

Topic Contents

Customizing Existing My Namespace Members

Adding Members to My Objects

Adding Custom Objects to the My Namespace

Adding Members to the My Namespace

Adding Events to Custom My Objects

Design Guidelines

Designing Class Libraries for My

Packaging and Deploying Extensions

Customizing Existing My Namespace Members


The My namespace in Visual Basic exposes frequently used information about your application, your computer, and more. For a complete list of the objects in the My
namespace, see My Reference (Visual Basic). You may have to customize existing members of the My namespace so that they better match the needs of your
application. Any property of an object in the My namespace that is not read-only can be set to a custom value.

For example, assume that you frequently use the My.User object to access the current security context for the user running your application. However, your company
uses a custom user object to expose additional information and capabilities for users within the company. In this scenario, you can replace the default value of the
My.User.CurrentPrincipal property with an instance of your own custom principal object, as shown in the following example.

VB

My.User.CurrentPrincipal = CustomPrincipal

Setting the CurrentPrincipal property on the My.User object changes the identity under which the application runs. The My.User object, in turn, returns information
about the newly specified user.

Adding Members to My Objects


The types returned from My.Application and My.Computer are defined as Partial classes. Therefore, you can extend the My.Application and My.Computer objects
by creating a Partial class named MyApplication or MyComputer. The class cannot be a Private class. If you specify the class as part of the My namespace, you can
add properties and methods that will be included with the My.Application or My.Computer objects.

For example, the following example adds a property named DnsServerIPAddresses to the My.Computer object.

VB

Imports System.Net.NetworkInformation

Namespace My

Partial Class MyComputer


Friend ReadOnly Property DnsServerIPAddresses() As IPAddressCollection
Get
Dim dnsAddressList As IPAddressCollection = Nothing

For Each adapter In System.Net.NetworkInformation.


NetworkInterface.GetAllNetworkInterfaces()

Dim adapterProperties = adapter.GetIPProperties()


Dim dnsServers As IPAddressCollection = adapterProperties.DnsAddresses
If dnsAddressList Is Nothing Then
dnsAddressList = dnsServers
Else
dnsAddressList.Union(dnsServers)
End If
Next adapter

Return dnsAddressList
End Get
End Property
End Class

End Namespace

Adding Custom Objects to the My Namespace


Although the My namespace provides solutions for many common programming tasks, you may encounter tasks that the My namespace does not address. For
example, your application might access custom directory services for user data, or your application might use assemblies that are not installed by default with Visual
Basic. You can extend the My namespace to include custom solutions to common tasks that are specific to your environment. The My namespace can easily be extended
to add new members to meet growing application needs. Additionally, you can deploy your My namespace extensions to other developers as a Visual Basic template.

Adding Members to the My Namespace


Because My is a namespace like any other namespace, you can add top-level properties to it by just adding a module and specifying a Namespace of My. Annotate
the module with the HideModuleName attribute as shown in the following example. The HideModuleName attribute ensures that IntelliSense will not display the
module name when it displays the members of the My namespace.

VB

Namespace My
<HideModuleName()>
Module MyCustomModule

End Module
End Namespace

To add members to the My namespace, add properties as needed to the module. For each property added to the My namespace, add a private field of type
ThreadSafeObjectProvider(Of T), where the type is the type returned by your custom property. This field is used to create thread-safe object instances to be
returned by the property by calling the GetInstance method. As a result, each thread that is accessing the extended property receives its own instance of the returned
type. The following example adds a property named SampleExtension that is of type SampleExtension to the My namespace:

VB

Namespace My
<HideModuleName()>
Module MyCustomExtensions
Private _extension As New ThreadSafeObjectProvider(Of SampleExtension)
Friend ReadOnly Property SampleExtension() As SampleExtension
Get
Return _extension.GetInstance()
End Get
End Property
End Module
End Namespace

Adding Events to Custom My Objects


You can use the My.Application object to expose events for your custom My objects by extending the MyApplication partial class in the My namespace. For Windows-
based projects, you can double-click the My Project node in for your project in Solution Explorer. In the Visual Basic Project Designer, click the Application tab and
then click the View Application Events button. A new file that is named ApplicationEvents.vb will be created. It contains the following code for extending the
MyApplication class.

VB

Namespace My
Partial Friend Class MyApplication
End Class
End Namespace

You can add event handlers for your custom My objects by adding custom event handlers to the MyApplication class. Custom events enable you to add code that will
execute when an event handler is added, removed, or the event is raised. Note that the AddHandler code for a custom event runs only if code is added by a user to
handle the event. For example, consider that the SampleExtension object from the previous section has a Load event that you want to add a custom event handler for.
The following code example shows a custom event handler named SampleExtensionLoad that will be invoked when the My.SampleExtension.Load event occurs. When
code is added to handle the new My.SampleExtensionLoad event, the AddHandler part of this custom event code is executed. The
MyApplication_SampleExtensionLoad method is included in the code example to show an example of an event handler that handles the My.SampleExtensionLoad
event. Note that the SampleExtensionLoad event will be available when you select the My Application Events option in the left drop-down list above the Code Editor
when you are editing the ApplicationEvents.vb file.

VB

Namespace My

Partial Friend Class MyApplication

' Custom event handler for Load event.


Private _sampleExtensionHandlers As EventHandler

Public Custom Event SampleExtensionLoad As EventHandler


AddHandler(ByVal value As EventHandler)
' Warning: This code is not thread-safe. Do not call
' this code from multiple concurrent threads.
If _sampleExtensionHandlers Is Nothing Then
AddHandler My.SampleExtension.Load, AddressOf OnSampleExtensionLoad
End If
_sampleExtensionHandlers =
System.Delegate.Combine(_sampleExtensionHandlers, value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
_sampleExtensionHandlers =
System.Delegate.Remove(_sampleExtensionHandlers, value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
If _sampleExtensionHandlers IsNot Nothing Then
_sampleExtensionHandlers.Invoke(sender, e)
End If
End RaiseEvent
End Event

' Method called by custom event handler to raise user-defined


' event handlers.
<Global.System.ComponentModel.EditorBrowsable(
Global.System.ComponentModel.EditorBrowsableState.Advanced)>
Protected Overridable Sub OnSampleExtensionLoad(
ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent SampleExtensionLoad(sender, e)
End Sub

' Event handler to call My.SampleExtensionLoad event.


Private Sub MyApplication_SampleExtensionLoad(
ByVal sender As Object, ByVal e As System.EventArgs
) Handles Me.SampleExtensionLoad

End Sub
End Class
End Namespace

Design Guidelines
When you develop extensions to the My namespace, use the following guidelines to help minimize the maintenance costs of your extension components.

Include only the extension logic. The logic included in the My namespace extension should include only the code that is needed to expose the required
functionality in the My namespace. Because your extension will reside in user projects as source code, updating the extension component incurs a high
maintenance cost and should be avoided if possible.

Minimize project assumptions. When you create your extensions of the My namespace, do not assume a set of references, project-level imports, or specific
compiler settings (for example, Option Strict off). Instead, minimize dependencies and fully qualify all type references by using the Global keyword. Also, ensure
that the extension compiles with Option Strict on to minimize errors in the extension.

Isolate the extension code. Placing the code in a single file makes your extension easily deployable as a Visual Studio item template. For more information, see
"Packaging and Deploying Extensions" later in this topic. Placing all the My namespace extension code in a single file or a separate folder in a project will also
help users locate the My namespace extension.

Designing Class Libraries for My


As is the case with most object models, some design patterns work well in the My namespace and others do not. When designing an extension to the My namespace,
consider the following principles:

Stateless methods. Methods in the My namespace should provide a complete solution to a specific task. Ensure that the parameter values that are passed to the
method provide all the input required to complete the particular task. Avoid creating methods that rely on prior state, such as open connections to resources.

Global instances. The only state that is maintained in the My namespace is global to the project. For example, My.Application.Info encapsulates state that is
shared throughout the application.

Simple parameter types. Keep things simple by avoiding complex parameter types. Instead, create methods that either take no parameter input or that take
simple input types such as strings, primitive types, and so on.

Factory methods. Some types are necessarily difficult to instantiate. Providing factory methods as extensions to the My namespace enables you to more easily
discover and consume types that fall into this category. An example of a factory method that works well is My.Computer.FileSystem.OpenTextFileReader. There
are several stream types available in the .NET Framework. By specifying text files specifically, the OpenTextFileReader helps the user understand which stream to
use.

These guidelines do not preclude general design principles for class libraries. Rather, they are recommendations that are optimized for developers who are using Visual
Basic and the My namespace. For general design principles for creating class libraries, see Design Guidelines for Developing Class Libraries.
Packaging and Deploying Extensions
You can include My namespace extensions in a Visual Studio project template, or you can package your extensions and deploy them as a Visual Studio item template.
When you package your My namespace extensions as a Visual Studio item template, you can take advantage of additional capabilities provided by Visual Basic. These
capabilities enable you to include an extension when a project references a particular assembly, or enable users to explicitly add your My namespace extension by using
the My Extensions page of the Visual Basic Project Designer.

For details about how to deploy My namespace extensions, see Packaging and Deploying Custom My Extensions (Visual Basic).

See Also
Reference
My Extensions Page, Project Designer (Visual Basic)
Application Page, Project Designer (Visual Basic)
Partial (Visual Basic)
Concepts
Packaging and Deploying Custom My Extensions (Visual Basic)
Extending the Visual Basic Application Model
Customizing Which Objects are Available in My (Visual Basic)

2014 Microsoft. All rights reserved.


Packaging and Deploying Custom My Extensions (Visual Basic)
Visual Studio 2012

Visual Basic provides an easy way for you to deploy your custom My namespace extensions by using Visual Studio templates. If you are creating a project template for
which your My extensions are an integral part of the new project type, you can just include your custom My extension code with the project when you export the template.
For more information about exporting project templates, see How to: Create Project Templates.

If your custom My extension is in a single code file, you can export the file as an item template that users can add to any type of Visual Basic project. You can then
customize the item template to enable additional capabilities and behavior for your custom My extension in a Visual Basic project. Those capabilities include the following:

Allowing users to manage your custom My extension from the My Extensions page of the Visual Basic Project Designer.

Automatically adding your custom My extension when a reference to a specified assembly is added to a project.

Hiding the My extension item template in the Add Item dialog box so that it is not included in the list of project items.

This topic discusses how to package a custom My extension as a hidden item template that can be managed from the My Extensions page of the Visual Basic Project
Designer. The custom My extension can also be added automatically when a reference to a specified assembly is added to a project.

Create a My Namespace Extension


The first step in creating a deployment package for a custom My extension is to create the extension as a single code file. For details and guidance about how to create
a custom My extension, see Extending the My Namespace in Visual Basic.

Export a My Namespace Extension as an Item Template


After you have a code file that includes your My namespace extension, you can export the code file as a Visual Studio item template. For instructions on how to export a
file as a Visual Studio item template, see How to: Create Item Templates.

Note

If your My namespace extension has a dependency on a particular assembly, you can customize your item template to automatically install your My namespace
extension when a reference to that assembly is added. As a result, you will want to exclude that assembly reference when you export the code file as a Visual Studio
item template.

Customize the Item Template


You can enable your item template to be managed from the My Extensions page of the Visual Basic Project Designer. You can also enable the item template to be
added automatically when a reference to a specified assembly is added to a project. To enable these customizations, you will add a new file, called the CustomData file,
to your template, and then add a new element to the XML in your .vstemplate file.

Add the CustomData File


The CustomData file is a text file that has a file name extension of .CustomData (the file name can be set to any value meaningful to your template) and that contains
XML. The XML in the CustomData file instructs Visual Basic to include your My extension when users use the My Extensions page of the Visual Basic Project Designer.
You can optionally add the <AssemblyFullName> attribute to your CustomData file XML. This instructs Visual Basic to automatically install your custom My extension
when a reference to a particular assembly is added to the project. You can use any text editor or XML editor to create the CustomData file, and then add it to your
item template's compressed folder (.zip file).

For example, the following XML shows the contents of a CustomData file that will add the template item to the My Extensions folder of a Visual Basic project when a
reference to the Microsoft.VisualBasic.PowerPacks.Vs.dll assembly is added to the project.

<VBMyExtensionTemplate
ID="Microsoft.VisualBasic.Samples.MyExtensions.MyPrinterInfo"
Version="1.0.0.0"
AssemblyFullName="Microsoft.VisualBasic.PowerPacks.vs"
/>

The CustomData file contains a <VBMyExtensionTemplate> element that has attributes as listed in the following table.

Attribute Description

ID Required. A unique identifier for the extension. If the extension that has this ID has already been added to the project, the user will not be
prompted to add it again.

Version Required. A version number for the item template.

AssemblyFullName Optional. An assembly name. When a reference to this assembly is added to the project, the user will be prompted to add the My extension
from this item template.

Add the <CustomDataSignature> Element to the .vstemplate File


To identify your Visual Studio item template as a My namespace extension, you must also modify the .vstemplate file for your item template. You must add a
<CustomDataSignature> element to the <TemplateData> element. The <CustomDataSignature> element must contain the text
Microsoft.VisualBasic.MyExtension, as shown in the following example.

<CustomDataSignature>Microsoft.VisualBasic.MyExtension</CustomDataSignature>

You cannot modify files in a compressed folder (.zip file) directly. You must copy the .vstemplate file from the compressed folder, modify it, and then replace the
.vstemplate file in the compressed folder with your updated copy.

The following example shows the contents of a .vstemplate file that has the <CustomDataSignature> element added.

<VSTemplate Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">


<TemplateData>
<DefaultName>MyCustomExtensionModule.vb</DefaultName>
<Name>MyPrinterInfo</Name>
<Description>Custom My Extensions Item Template</Description>
<ProjectType>VisualBasic</ProjectType>
<SortOrder>10</SortOrder>
<Icon>__TemplateIcon.ico</Icon>
<CustomDataSignature
>Microsoft.VisualBasic.MyExtension</CustomDataSignature>
</TemplateData>
<TemplateContent>
<References />
<ProjectItem SubType="Code"
TargetFileName="$fileinputname$.vb"
ReplaceParameters="true"
>MyCustomExtensionModule.vb</ProjectItem>
</TemplateContent>
</VSTemplate>

Install the Template


To install the template, you can copy the compressed folder (.zip file) to the Visual Basic item templates folder (for example, My Documents\Visual Studio
2008\Templates\Item Templates\Visual Basic). Alternatively, you can publish the template as a Visual Studio Installer (.vsi) file. For information about publishing your
template as a Visual Studio Installer file, see How to: Publish Project Templates.

See Also
Reference
My Extensions Page, Project Designer (Visual Basic)
Concepts
Extending the My Namespace in Visual Basic
Extending the Visual Basic Application Model
Customizing Which Objects are Available in My (Visual Basic)

2014 Microsoft. All rights reserved.


Extending the Visual Basic Application Model
Visual Studio 2012

You can add functionality to the application model by overriding the Overridable members of the WindowsFormsApplicationBase class. This technique allows you to
customize the behavior of the application model and add calls to your own methods as the application starts up and shuts down.

Visual Overview of the Application Model


This section visually presents the sequence of function calls in the Visual Basic Application Model. The next section describes the purpose of each function in detail.

The following graphic shows the application model call sequence in a normal Visual Basic Windows Forms application. The sequence starts when the Sub Main
procedure calls the Run method.

The Visual Basic Application Model also provides the StartupNextInstance and UnhandledException events. The following graphics show the mechanism for raising these
events.

Overriding the Base Methods


The Run method defines the order in which the Application methods run. By default, the Sub Main procedure for a Windows Forms application calls the Run method.

If the application is a normal application (multiple-instance application), or the first instance of a single-instance application, the Run method executes the Overridable
methods in the following order:

1. OnInitialize . By default, this method sets the visual styles, text display styles, and current principal for the main application thread (if the application uses Windows
authentication), and calls ShowSplashScreen if neither /nosplash nor -nosplash is used as a command-line argument.

The application startup sequence is canceled if this function returns False. This can be useful if there are circumstances in which the application should not run.

The OnInitialize method calls the following methods:

a. ShowSplashScreen . Determines if the application has a splash screen defined and if it does, displays the splash screen on a separate thread.

The ShowSplashScreen method contains the code that displays the splash screen for at least the number of milliseconds specified by the
MinimumSplashScreenDisplayTime property. To use this functionality, you must add the splash screen to your application using the Project Designer
(which sets the My.Application.MinimumSplashScreenDisplayTime property to two seconds), or set the
My.Application.MinimumSplashScreenDisplayTime property in a method that overrides the OnInitialize or OnCreateSplashScreen method. For more
information, see MinimumSplashScreenDisplayTime.

b. OnCreateSplashScreen . Allows a designer to emit code that initializes the splash screen.

By default, this method does nothing. If you select a splash screen for your application in the Visual Basic Project Designer, the designer overrides the
OnCreateSplashScreen method with a method that sets the SplashScreen property to a new instance of the splash-screen form.

2. OnStartup . Provides an extensibility point for raising the Startup event. The application startup sequence stops if this function returns False.
By default, this method raises the Startup event. If the event handler sets the Cancel property of the event argument to True, the method returns False to cancel
the application startup.

3. OnRun . Provides the starting point for when the main application is ready to start running, after the initialization is done.

By default, before it enters the Windows Forms message loop, this method calls the OnCreateMainForm (to create the application's main form) and
HideSplashScreen (to close the splash screen) methods:

a. OnCreateMainForm . Provides a way for a designer to emit code that initializes the main form.

By default, this method does nothing. However, when you select a main form for your application in the Visual Basic Project Designer, the designer
overrides the OnCreateMainForm method with a method that sets the MainForm property to a new instance of the main form.

b. HideSplashScreen . If application has a splash screen defined and it is open, this method closes the splash screen.

By default, this method closes the splash screen.

4. OnStartupNextInstance . Provides a way to customize how a single-instance application behaves when another instance of the application starts.

By default, this method raises the StartupNextInstance event.

5. OnShutdown . Provides an extensibility point for raising the Shutdown event. This method does not run if an unhandled exception occurs in the main application.

By default, this method raises the Shutdown event.

6. OnUnhandledException . Executed if an unhandled exception occurs in any of the above listed methods.

By default, this method raises the UnhandledException event as long as a debugger is not attached and the application is handling the UnhandledException
event.

If the application is a single-instance application, and the application is already running, the subsequent instance of the application calls the OnStartupNextInstance
method on the original instance of the application, and then exits.

The WindowsFormsApplicationBase constructor calls the UseCompatibleTextRendering property to determine which text rendering engine to use for the application's
forms. By default, the UseCompatibleTextRendering property returns False, indicating that the GDI text rendering engine be used, which is the default in Visual Basic
2005. You can override the UseCompatibleTextRendering property to return True, which indicates that the GDI+ text rendering engine be used, which is the default in
Visual Basic .NET 2002 and Visual Basic .NET 2003.

Configuring the Application


As a part of the Visual Basic Application model, the WindowsFormsApplicationBase class provides protected properties that configure the application. These properties
should be set in the constructor of the implementing class.

In a default Windows Forms project, the Project Designer creates code to set the properties with the designer settings. The properties are used only when the
application is starting; setting them after the application starts has no effect.

Property Determines Setting in the Application pane of the Project


Designer

IsSingleInstance Whether the application runs as a single-instance or multiple-instance application. Make single instance application check box

EnableVisualStyles If the application will use visual styles that match Windows XP. Enable XP visual styles check box

SaveMySettingsOnExit If application automatically saves application's user-settings changes when the application Save My.Settings on Shutdown check box
exits.

ShutdownStyle What causes the application to terminate, such as when the startup form closes or when the Shutdown mode list
last form closes.

See Also
Reference
ApplicationBase
Startup
StartupNextInstance
UnhandledException
Shutdown
NetworkAvailabilityChanged
WindowsFormsApplicationBase
Application Page, Project Designer (Visual Basic)
Concepts
Overview of the Visual Basic Application Model

2014 Microsoft. All rights reserved.


Customizing Which Objects are Available in My (Visual Basic)
Visual Studio 2012

This topic describes how you can control which My objects are enabled by setting your project's _MYTYPE conditional-compilation constant. The Visual Studio Integrated
Development Environment (IDE) keeps the _MYTYPE conditional-compilation constant for a project in sync with the project's type.

Predefined _MYTYPE Values


You must use the /define compiler option to set the _MYTYPE conditional-compilation constant. When specifying your own value for the _MYTYPE constant, you must
enclose the string value in backslash/quotation mark (\") sequences. For example, you could use:

/define:_MYTYPE=\"WindowsForms\"

This table shows what the _MYTYPE conditional-compilation constant is set to for several project types.

Project type _MYTYPE value

Class Library "Windows"

Console Application "Console"

Web "Web"

Web Control Library "WebControl"

Windows Application "WindowsForms"

Windows Application, when starting with custom Sub Main "WindowsFormsWithCustomSubMain"

Windows Control Library "Windows"

Windows Service "Console"

Empty "Empty"

Note

All conditional-compilation string comparisons are case-sensitive, regardless of how the Option Compare statement is set.

Dependent _MY Compilation Constants


The _MYTYPE conditional-compilation constant, in turn, controls the values of several other _MY compilation constants:

_MYTYPE _MYAPPLICATIONTYPE _MYCOMPUTERTYPE _MYFORMS _MYUSERTYPE _MYWEBSERVICES

"Console" "Console" "Windows" Undefined "Windows" TRUE

"Custom" Undefined Undefined Undefined Undefined Undefined

"Empty" Undefined Undefined Undefined Undefined Undefined

"Web" Undefined "Web" FALSE "Web" FALSE

"WebControl" Undefined "Web" FALSE "Web" TRUE

"Windows" or "" "Windows" "Windows" Undefined "Windows" TRUE

"WindowsForms" "WindowsForms" "Windows" TRUE "Windows" TRUE

"WindowsFormsWithCustomSubMain" "Console" "Windows" TRUE "Windows" TRUE

By default, undefined conditional-compilation constants resolve to FALSE. You can specify values for the undefined constants when compiling your project to override
the default behavior.

Note

When _MYTYPE is set to "Custom", the project contains the My namespace, but it contains no objects. However, setting _MYTYPE to "Empty" prevents the compiler
from adding the My namespace and its objects.

This table describes the effects of the predefined values of the _MY compilation constants.
Constant Meaning

_MYAPPLICATIONTYPE Enables My.Application, if the constant is "Console," Windows," or "WindowsForms":

The "Console" version derives from ConsoleApplicationBase. and has fewer members than the "Windows" version.
The "Windows" version derives from ApplicationBase.and has fewer members than the "WindowsForms" version.
The "WindowsForms" version of My.Application derives from WindowsFormsApplicationBase. If the TARGET constant is defined to
be "winexe", then the class includes a Sub Main method.

_MYCOMPUTERTYPE Enables My.Computer, if the constant is "Web" or "Windows":

The "Web" version derives from ServerComputer, and has fewer members than the "Windows" version.
The "Windows" version of My.Computer derives from Computer.

_MYFORMS Enables My.Forms, if the constant is TRUE.

_MYUSERTYPE Enables My.User, if the constant is "Web" or "Windows":

The "Web" version of My.User is associated with the user identity of the current HTTP request.
The "Windows" version of My.User is associated with the thread's current principal.

_MYWEBSERVICES Enables My.WebServices, if the constant is TRUE.

_MYTYPE Enables My.Log, My.Request, and My.Response, if the constant is "Web".

See Also
Reference
/define (Visual Basic)
ApplicationBase
Computer
My.Forms Object
Log
My.Request Object
My.Response Object
User
My.WebServices Object
Concepts
How My Depends on Project Type (Visual Basic)
Other Resources
Conditional Compilation in Visual Basic

2014 Microsoft. All rights reserved.