How to: Write a Text 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 a Text File (C++/CLI)

The following code example demonstrates how to create a text file and write text to it using the StreamWriter class, which is defined in the System.IO namespace. The StreamWriter constructor takes the name of the file to be created. If the file exists, it is overwritten (unless you pass True as the second StringWriter constructor argument).

The file is then filed using the Write and WriteLine functions.

// text_write.cpp
// compile with: /clr
using namespace System;
using namespace System::IO;

int main() 
   String^ fileName = "textfile.txt";

   StreamWriter^ sw = gcnew StreamWriter(fileName);
   sw->WriteLine("A text file is born!");
   sw->Write("You can use WriteLine");
   sw->WriteLine("...or just Write");
   sw->WriteLine("and do {0} output too.", "formatted");
   sw->WriteLine("You can also send non-text objects:");
   Console::WriteLine("a new file ('{0}') has been written", fileName);

   return 0;
© 2015 Microsoft