Code: Writing to a Text File (Visual C#)
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"); file.WriteLine(lines); file.Close();
Compiling the Code
Copy the code and paste it into the Main method of a console application.
"c:\\test.txt" with the actual file name.
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).
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);
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