Académique Documents
Professionnel Documents
Culture Documents
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
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.
1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.
VB
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
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
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.
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
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
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.
1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file test.log.
VB
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
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
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.
1. Add a text file named testfile.txt to your project. Add the following content to the text file.
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
VB
VB
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.
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
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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)
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.
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
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
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.
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.
1. Create a Click event handler for browseButton by double-clicking the control on the form. The Code Editor opens.
VB
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.
VB
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.
1. Create a Click event handler for examineButton by double-clicking the control on the form.
VB
' 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
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.
VB
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.
1. Add the following code to the end of the examineButton_Click event handler.
VB
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.
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.
VB
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.
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
SetEnabled()
End Sub
' 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
Return sb.ToString
End Function
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
VB
SetEnabled()
End Sub
' 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
System.IO.File.AppendAllText(logFilePath, logText)
End If
End Sub
Return sb.ToString
End Function
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
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.
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.
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
2. Make sure that the user cannot submit a blank entry by adding the following code directly after Dim ReadString As String.
VB
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
4. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.
VB
Entry.Text = ""
For this section of the walkthrough, add the controls in the following table to the form and set the corresponding values for their properties.
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
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.
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
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.
Add the controls in the following table to the form and set the corresponding values for their properties.
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
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.
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
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.
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
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.
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.
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
VB
My.Computer.Clipboard.Clear()
VB
VB
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
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
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.
See Also
Other Resources
Visual Basic Language Features
Programming Concepts
Collections (C# and Visual Basic)
Developing Applications with Visual Basic
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.
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
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.
In general, when an application plays a looping sound, it should stop the sound at some point.
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.
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
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.
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.
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
VB
My.Computer.Clipboard.Clear()
VB
VB
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
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
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
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
Start an application and send it keystrokes How to: Start an Application and Send it Keystrokes (Visual Basic)
See Also
Reference
Keyboard
Keys
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
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
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 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
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.
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.
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")
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)
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:
See Also
Tasks
How to: Download a File in Visual Basic
How to: Parse File Paths in Visual Basic
Reference
Network
UploadFile
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 server does not respond within the specified connectionTimeout (TimeoutException).
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")
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)
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
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.
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
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.
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.
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.
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).
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
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
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
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.
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
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.
VB
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
This topic describes how to use My.Computer.Ports to receive strings from the computer's serial ports in Visual Basic.
VB
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
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
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
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
VB
Return returnStr
Example
VB
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.
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
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.
SerialData Specifies the type of character that was received on the serial port of 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)
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.
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.
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.
The CreateSubKey method of the My.Computer.Registry object can be used to create a registry key.
Procedure
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")
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 user does not have permissions to create registry keys (SecurityException).
See Also
Reference
RegistryProxy
CurrentUser
CreateSubKey
Concepts
Code Access Security Basics
Other Resources
Reading from and Writing to the Registry (Visual Basic)
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.
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
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.
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 user does not have permissions to read from registry keys (SecurityException).
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)
The DeleteSubKey(String) and DeleteSubKey(String, Boolean) methods can be used to delete registry keys.
Procedure
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 user does not have permissions to delete registry keys (SecurityException).
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)
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.
Key Description
ClassesRoot Defines the types of documents and the properties associated with those types.
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.
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.
VB
The following code reads, increments, and then writes a string to HKEY_CURRENT_USER.
VB
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)
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.
Create Create
NoAccess No access
Read Read
Write Write
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)
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
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
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
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
VB
VB
Try
Catch ex As Exception
End Try
3. Put the code that could generate an exception in the Try block.
VB
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
1. Have a project selected in Solution Explorer. On the Project menu, choose Properties.
3. Click the View Application Events button to open the Code Editor.
4. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.
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
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
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.
1. Have a project selected in Solution Explorer. On the Project menu, choose Properties.
3. Click the View Application Events button to open the Code Editor.
1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.
The application raises the Startup event before the main application runs.
VB
1. Have the ApplicationEvents.vb file open in the Code Editor. On the General menu, choose MyApplication Events.
The application raises the Shutdown event after the main application runs, but before it shuts down.
VB
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
See Also
Reference
Application Page, Project Designer (Visual Basic)
Microsoft.VisualBasic.Logging.Log
WriteEntry
WriteException
Concepts
Working with Application Logs in Visual Basic
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.
- or -
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
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.
<add name="EventLog"/>
4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
<add name="EventLog"
type="System.Diagnostics.EventLogTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="APPLICATION_NAME"/>
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).
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
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.
- or -
b. From the Add New Item dialog box, choose Application Configuration File.
c. Click Add.
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.
4. Locate the <sharedListeners> section in the <system.diagnostics> section, nested under the top-level <configuration> 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\" />
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.
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
The My.Applicaton.Log and My.Log objects make it easy to write logging and tracing information to logs.
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.
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
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.
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>
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.
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
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.
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.
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 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.
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
- or -
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.
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.
<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:
To reconfigure a listener
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.
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.
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:
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
This is the output, and it can be used to uniquely reference a strongly named type, as in the "To add listeners" procedure above.
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
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.
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.
This table shows the severity level required for Log to write a message to the listeners, given a particular DefaultSwitch setting.
Critical Critical
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.
Note
The DefaultSwitch switch setting controls only My.Application.Log. It does not change how the .NET Framework Trace and Debug classes behave.
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.
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:
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)
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.
In your application, create a class named SimpleListener that inherits from TraceListener.
VB
<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.
1. Have a project selected in Solution Explorer. On the Project menu, choose Properties. For more information, see Introduction to the Project Designer.
4. Select <New> from the Choose a strong name key file drop-down list.
5. Provide a name for the key file in the Key file name box.
7. Click OK.
The following code shows how to determine the strongly named type name for SimpleListener.
VB
With the strong name, you can add the listener to the My.Application.Log log-listener collection.
-or-
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.
4. Locate the <sharedListeners> section, in the <system.diagnostics> section, in the top-level <configuration> section.
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
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.
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
Return ret
End Function
3. Pass the collection of the log's trace listeners to the GetListeners function, and display the return value.
VB
See Also
Tasks
Walkthrough: Determining Where My.Application.Log Writes Information (Visual Basic)
Reference
Log
Concepts
Working with Application Logs in Visual Basic
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 domain name, if the application uses Windows authentication CurrentPrincipal
See Also
Reference
User
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
Update the splash screen with status information as the application starts. SplashScreen
See Also
Reference
My.Forms Object
OpenForms
SplashScreen
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 asynchronously and handle an event when it completes How to: Call a Web Service Asynchronously (Visual Basic)
See Also
Reference
My.WebServices Object
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.
http://www.xmethods.net/sd/2001/DemoTemperatureService.wsdl
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:
4. Add a method to add the event handler to the getTempCompleted event, if necessary, and to call the getTempAsynch method:
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)
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
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.
1. Add the PropertyGrid control from the Toolbox to the design surface for your application, assumed here to be Form1.
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
VB
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
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.
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
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
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
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
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.
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.
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
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 Text Files with Multiple Formats in Visual Basic
Demonstrates how to read from a text file with multiple formats.
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.
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.
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
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
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.
1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.
VB
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
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
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.
1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file test.log.
VB
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
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
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.
1. Add a text file named testfile.txt to your project. Add the following content to the text file.
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
VB
VB
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.
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
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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)
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.
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
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
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: 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.
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.
The WriteAllText method can be used to write text to files. If the specified file does not exist, it is created.
Procedure
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)
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
The WriteAllText method can be used to append to a text file by specifying that the append parameter is set to True.
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
See Also
Reference
WriteAllText
FileSystem
Other Resources
Writing to Files in Visual Basic
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.
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
See Also
Tasks
How to: Write Text to Files in Visual Basic
Reference
WriteAllBytes
The My.Computer.FileSystem.SpecialDirectories object allows you to access special directories, such as the MyDocuments directory.
Procedure
VB
VB
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
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
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
Robust Programming
The following conditions may cause an exception:
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
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: Retrieve the Contents of the My Documents Directory in Visual Basic
Demonstrates how to read from special directories.
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.
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.
You can use the CopyFile method to copy the files 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
2. Use the CopyFile method to copy the files. This example copies the files to the directory named testdirectory.
VB
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
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).
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
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.
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)
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 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).
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
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.
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")
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 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).
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
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"
End Module
Robust Programming
If the file already exists, it is replaced.
The path name is malformed. For example, it contains illegal characters or is only white space (ArgumentException).
Security
A SecurityException may be thrown in partial-trust environments.
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
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.
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)
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).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
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.
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
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).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
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")
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 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).
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
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).
There is an existing file or directory with the name specified in newName (IOException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
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.
Use the CopyDirectory method, specifying source and destination directory names. The following example copies the directory named TestDirectory1 into
TestDirectory2, overwriting existing files.
VB
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 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).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
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 user does not have permission to create the directory (UnauthorizedAccessException).
See Also
Reference
CreateDirectory
Other Resources
Creating, Deleting, and Moving Files and Directories in Visual Basic
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.
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
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).
One or more of the specified wildcard characters is Nothing, an empty string, or contains only spaces (ArgumentNullException).
A file or folder name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
See Also
Tasks
How to: Find Files with a Specific Pattern in Visual Basic
Reference
GetDirectories
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.
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
The SpecialDirectories object can be used to read from many of the All Users directories, such as My Documents or Desktop.
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
See Also
Reference
SpecialDirectories
ReadAllText
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.
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
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
See Also
Tasks
How to: Get the Collection of Files in a Directory in Visual Basic
Reference
FileSystem
CombinePath
FileInfo
GetFileInfo
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.
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
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.
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
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
See Also
Other Resources
Reading from Files in Visual Basic
Writing to Files in Visual Basic
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
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.
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 .
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
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
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.
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
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
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.
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.
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.
FileIOPermission Controls the access of files and folders by defining Read, Write, Append and PathDiscovery permissions.
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.
Class Description
BinaryReader Reads encoded strings and primitive data types from 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
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.
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.
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
2. Make sure that the user cannot submit a blank entry by adding the following code directly after Dim ReadString As String.
VB
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
4. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.
VB
Entry.Text = ""
For this section of the walkthrough, add the controls in the following table to the form and set the corresponding values for their properties.
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
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.
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
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.
Add the controls in the following table to the form and set the corresponding values for their properties.
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
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.
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.
1. Create a Click event handler for browseButton by double-clicking the control on the form. The Code Editor opens.
VB
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.
VB
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.
1. Create a Click event handler for examineButton by double-clicking the control on the form.
VB
' 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
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.
VB
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.
1. Add the following code to the end of the examineButton_Click event handler.
VB
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.
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.
VB
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.
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
SetEnabled()
End Sub
' 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
Return sb.ToString
End Function
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
VB
SetEnabled()
End Sub
' 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
System.IO.File.AppendAllText(logFilePath, logText)
End If
End Sub
Return sb.ToString
End Function
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
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 Text Files with Multiple Formats in Visual Basic
Demonstrates how to read from a text file with multiple formats.
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.
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.
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
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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
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.
1. Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.
VB
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
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
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.
1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file test.log.
VB
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
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
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.
1. Add a text file named testfile.txt to your project. Add the following content to the text file.
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
VB
VB
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
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.
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
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)
The My.Computer.FileSystem object provides the ReadAllBytes method for reading from binary files.
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
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
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).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
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)
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.
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
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
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 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 a Form by Using the PrintForm Component (Visual Basic)
Explains how to print a basic form by using the PrintForm component.
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.
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.
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.
BeginPrint event. Occurs when the Print method is called and before the first page of the document prints.
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.
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
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.
1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.
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)
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.
1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.
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)
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.
1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.
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)
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.
1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.
3. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).
PrintForm1.Print()
1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.
3. Add the following code in the appropriate event handler (for example, in the Click event handler for a Print Button).
PrintForm1.Print()
1. In the Toolbox, click the Visual Basic PowerPacks tab and then drag the PrintForm component onto the form.
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)
If you want to deploy an application that references the PrintForm component, the component must be installed on the destination computer.
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)
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
Related Sections
Development with My (Visual Basic)
Describes which My objects are available in different project types by default.
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
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
Design Guidelines
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.
For example, the following example adds a property named DnsServerIPAddresses to the My.Computer object.
VB
Imports System.Net.NetworkInformation
Namespace My
Return dnsAddressList
End Get
End Property
End Class
End 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
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
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.
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)
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.
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.
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.
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.
<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.
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)
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.
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.
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.
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.
4. OnStartupNextInstance . Provides a way to customize how a single-instance application behaves when another instance of the application starts.
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.
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.
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.
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
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.
/define:_MYTYPE=\"WindowsForms\"
This table shows what the _MYTYPE conditional-compilation constant is set to for several project types.
Web "Web"
Empty "Empty"
Note
All conditional-compilation string comparisons are case-sensitive, regardless of how the Option Compare statement is set.
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
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.
The "Web" version derives from ServerComputer, and has fewer members than the "Windows" version.
The "Windows" version of My.Computer derives from Computer.
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.
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