How to: Write Text to Files in the My Documents Directory in Visual Basic

The My.Computer.FileSystem.SpecialDirectories object allows you to access special directories, such as the MyDocuments directory.

Procedure

To write new text files in the My Documents directory

  1. Use the My.Computer.FileSystem.SpecialDirectories.MyDocuments property to supply the path.

    Dim filePath As String
    filePath = System.IO.Path.Combine(
    My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
    
  2. Use the WriteAllText method to write text to the specified file.

    My.Computer.FileSystem.WriteAllText(filePath, "some text", True)
    

Example

Try
    Dim filePath As String
    filePath = System.IO.Path.Combine(
               My.Computer.FileSystem.SpecialDirectories.MyDocuments, "test.txt")
    My.Computer.FileSystem.WriteAllText(filePath, "some text", False)
Catch fileException As Exception
    Throw fileException
End Try

Compiling the Code

Replace test.txt with the name of the file you want to write to.

Robust Programming

This code rethrows all the exceptions that may occur when writing text to the file. You can reduce the likelihood of exceptions by using Windows Forms controls such as the OpenFileDialog and the SaveFileDialog components that limit the user choices to valid file names. Using these controls is not foolproof, however. The file system can change between the time the user selects a file and the time that the code executes. Exception handling is therefore nearly always necessary when with working with files.

.NET Framework 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