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.
Example
// 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");
file.WriteLine(lines);
file.Close();
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:
- The file exists and is read-only (IOException).
- The path name may be too long (PathTooLongException).
- The disk may be full (IOException).
Security
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