How to: Read From Existing Text Files in My Documents (Visual Basic)

The following code example reads the contents of the text files in the My Documents folder into a single file.

Example

Dim filePaths As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
Dim allText As String 
Try
   filePaths = My.Computer.FileSystem.GetFiles _
   (My.Computer.FileSystem.SpecialDirectories.MyDocuments)
   For Each file As String In filePaths
      allText = My.Computer.FileSystem.ReadAllText(file)
      My.Computer.FileSystem.WriteAllText("bigfile.txt", allText, True)
   Next 
Catch fileException As Exception
   Throw fileException
End Try

Compiling the Code

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

Robust Programming

The files that are read must be text files.

You can use the OpenFileDialog Component (Windows Forms) and the SaveFileDialog Component (Windows Forms) to reduce the likelihood of permissions-related run-time errors.

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 Access Control Lists (ACLs).

See Also

Reference

My.Computer.FileSystem.SpecialDirectories Object

My.Computer.FileSystem.ReadAllText Method

My.Computer.FileSystem.WriteAllText Method

OpenFileDialog

SaveFileDialog