How to: Write Text to a File
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

How to: Write Text to a File

Updated: January 2010

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.

NoteNote:

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.

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());
        }
    }
}

Date

History

Reason

January 2010

Improved example.

Customer feedback.

Show:
© 2016 Microsoft