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 namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Collections::Generic;

ref class Program
{
public:
    static void Main()
    {
        String^ mydocpath =
        	Environment::GetFolderPath(Environment::SpecialFolder::MyDocuments);
        StringBuilder^ sb = gcnew StringBuilder();

        for each (String^ txtName in Directory::EnumerateFiles(mydocpath, "*.txt"))
        {
            StreamReader^ sr = gcnew StreamReader(txtName);
            sb->AppendLine(txtName->ToString());
            sb->AppendLine("= = = = = =");
            sb->Append(sr->ReadToEnd());
            sb->AppendLine();
            sb->AppendLine();
            sr->Close();
        }

        StreamWriter^ outfile = gcnew StreamWriter(mydocpath + "\\AllTxtFiles.txt");
        outfile->Write(sb->ToString());
        outfile->Close();
    }
};

int main()
{
    Program::Main();
}


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

Community Additions

ADD
Show:
© 2014 Microsoft