Windows Dev Center

Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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.


using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

class Program
{

    static void Main(string[] args)
    {

        string mydocpath = 
        	Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        StringBuilder sb = new StringBuilder();

        foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt"))
        {
            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());
        }
    }
}


Community Additions

Show:
© 2015 Microsoft