Write to Text File in C#
Writing to a text file in C# involves a few simple steps:
- Create a StreamWriter object
- Write to the file
- Close the StreamWriter object
Create a StreamWriter object
To write to a text file, you will first need to create a StreamWriter object. The StreamWriter class provides methods to write to a text file. You will need to specify the file path and name to create the StreamWriter object.
Following is an example of how to create a StreamWriter object:
Write to the file
Once you have created the StreamWriter object, you can use its methods to write to the file. The most common method is the Write method, which writes a string to the file. The WriteLine method can also be used to write a string with a newline character at the end.
Following is an example of how to write to a file using the StreamWriter object:
Close the StreamWriter object
After you have finished writing to the file, you should close the StreamWriter object to release any resources it is using. You can do this by calling the Close method on the object.
Following is an example of how to close the StreamWriter object:
Write to a text file | C#

Putting it all together, Following is an example of how to write to a text file in C#:
This will create a file named "file.txt" in the same directory as the program and write the text "Hello, world!" and "This is a new line." to the file.
Write a collection of strings to a file in C#
To write a collection of strings to a file in C#, you can use the StreamWriter class to create a new file or overwrite an existing file with the contents of the collection. Here are the steps to write a collection of strings to a file in C#:
This will create a new file named "file.txt" in the same directory as the program and write each string from the collection on a new line in the file. If the file already exists, it will be overwritten.
- C# Crystal Reports Tutorial
- CSharp Communication Tutorial
- Threading in C#
- C# Ado.Net Tutorial and Source Code , c# database programming tutorial
- C# ADO.NET data Providers Tutorial
- C# Dataset Tutorial
- C# DataAdapater Tutorial
- Csharp DataView Tutorial
- Csharp Remoting Tutorial
- C# XML Tutorial
- C# DataGridView Tutorial
- C# Advanced Topics