Code: Writing to a Text File (Visual C#)
The document is archived and information here might be outdated

Code: Writing to a Text File (Visual C#)

Visual Studio .NET 2003

This example writes a string to a text file using the WriteLine method of the StreamWriter class.


// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");


Compiling the Code

Copy the code and paste it into the Main method of a console application.

Replace "c:\\test.txt" with the actual file name.

Robust Programming

The following conditions may cause an exception:


This example creates a new file, if one does not already exist. If the file already exists, the application will overwrite it.

In order to append an existing file, set the Boolean parameter to true, as follows:

System.IO.StreamWriter file =
   new System.IO.StreamWriter("c:\\test.txt", true);

See Also

Code: Reading a Text File One Line at a Time (Visual C#) | Code: Reading From a Text File (Visual C#) | File Access Through StreamReader and StreamWriter Classes | StreamWriter Class | General Language Example Topics

© 2016 Microsoft