How to: Write Text to a File

The following example shows how to write text to a text file. It reads all the text files from the user's My Documents folder by using a "*.txt" search pattern, and writes them into a large text file.

NoteNote

Visual Basic users may choose to use the methods and properties provided by the Microsoft.VisualBasic.FileIO.FileSystem class for file I/O.


Imports System
Imports System.IO
Imports System.Text
Imports System.Collections.Generic

Class Program

    Public Shared Sub Main(ByVal args As String())

        Dim mydocpath As String = _
        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim sb As New StringBuilder()

        For Each txtName As String _
            In Directory.EnumerateFiles(mydocpath, "*.txt")
            Using sr As New StreamReader(txtName)
                sb.AppendLine(txtName.ToString())
                sb.AppendLine("= = = = = =")
                sb.Append(sr.ReadToEnd())
                sb.AppendLine()
                sb.AppendLine()

            End Using
        Next

        Using outfile As New StreamWriter(mydocpath & "\AllTxtFiles.txt")
            outfile.Write(sb.ToString())
        End Using
    End Sub
End Class


Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft