How to: Write Text to a File

The following code example shows how to write text to a text file.

It reads all the text flies, using a "*.txt" search pattern, from the user's documents folder and writes them into a large text file.

Note

Visual Basic users may choose to use the methods and properties provided by the My.Computer.FileSystem object for file I/O. For more information, see My.Computer.FileSystem Object.

Example

Imports System
Imports System.IO
Imports System.Text

Class Program

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

        Dim mydocpath As String = _
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        Dim txtList As String() = Directory.GetFiles(mydocpath, "*.txt")
        Dim sb As New StringBuilder()

        For Each txtName As String In txtList
            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
using System;
using System.IO;
using System.Text;

class Program
{

    static void Main(string[] args)
    {

        string mydocpath = 
          Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string[] txtList = Directory.GetFiles(mydocpath, "*.txt");
        StringBuilder sb = new StringBuilder();

        foreach (string txtName in txtList)
        {
            using (StreamReader sr = new StreamReader(txtName))
            {
                sb.AppendLine(txtName.ToString());
                sb.AppendLine("= = = = = =");
                sb.Append(sr.ReadToEnd());
                sb.AppendLine();
                sb.AppendLine();
            }

        }

        using (StreamWriter outfile = 
            new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
        {
            outfile.Write(sb.ToString());
        }
    }
}

See Also

Tasks

How to: Create a Directory Listing

How to: Read and Write to a Newly Created Data File

How to: Open and Append to a Log File

How to: Read Text from a File

How to: Read Characters from a String

How to: Write Characters to a String

Concepts

Basic File I/O

Reference

StreamWriter

File.CreateText

Change History

Date

History

Reason

January 2010

Improved example.

Customer feedback.