File Handling in C# Using StreamWriter
Introduction
Writing to files is a routine task in many C# applications—from logging and configuration saving to generating reports and exporting data. The StreamWriter class makes it easy to write text data to files with high performance and minimal code.
StreamWriter
is part of the System.IO
namespace and allows writing to text files line-by-line or all at once. It supports both creating new files and appending to existing ones. Whether you're building a web app or a desktop tool, mastering StreamWriter is a key skill in .NET development.
Basic Usage of StreamWriter
The simplest way to write text to a file in C# is using a StreamWriter
inside a using
block. This ensures the writer is properly disposed after use.
using System.IO;
class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine("Hello, world!");
writer.WriteLine("This is a file written with StreamWriter.");
}
}
}
This creates output.txt
(or overwrites it if it exists) and writes two lines of text. WriteLine()
adds a newline after the string; Write()
writes without a newline.
Appending to an Existing File
To avoid overwriting a file, you can enable appending by passing true
as the second argument to the StreamWriter
constructor:
using (StreamWriter writer = new StreamWriter("log.txt", true))
{
writer.WriteLine("Log entry at " + DateTime.Now);
}
This is useful for creating log files, user history, or appending data over time.
Handling Exceptions While Writing Files
Writing to files may fail due to various issues—disk errors, access violations, or locked files. Wrapping your StreamWriter logic in a try-catch
block helps catch and handle these exceptions gracefully.
try
{
using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine("Logging data...");
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("Access denied: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("File I/O error: " + ex.Message);
}
This ensures your application doesn’t crash and provides meaningful messages when writing fails.
Writing with Specific Encoding
StreamWriter
supports encoding options like UTF-8, UTF-32, ASCII, etc. This is useful when dealing with multilingual files or integrating with systems that require specific encodings.
using (StreamWriter writer = new StreamWriter("utf8file.txt", false, Encoding.UTF8))
{
writer.WriteLine("Text written using UTF-8 encoding.");
}
Specifying encoding ensures compatibility, especially when exchanging files between different platforms.
Writing Arrays and Lists to a File
You can write collections like arrays or lists to a file line-by-line using a simple loop. This is useful for exporting data or generating reports.
string[] fruits = { "Apple", "Banana", "Cherry" };
using (StreamWriter writer = new StreamWriter("fruits.txt"))
{
foreach (string fruit in fruits)
{
writer.WriteLine(fruit);
}
}
This method ensures each item in your list appears on a new line in the file.
Real-World Use Cases
- Logging Systems: Append timestamped entries to a text-based log file.
- Exporting Reports: Save CSV or TXT data to share or archive.
- User Feedback: Store form submissions or comments locally.
- Audit Trails: Maintain simple, tamper-resistant activity logs.
- Error Tracking: Write application errors or stack traces for debugging.
Because it's simple, flexible, and efficient, StreamWriter
is ideal for almost every kind of text output your application needs.
Best Practices for StreamWriter
- Always use a
using
block to ensure the file stream is properly closed. - Use
Append
mode only when necessary to prevent unnecessary file growth. - Flush output manually using
writer.Flush()
if needed before closing for real-time logging. - Handle encoding correctly to avoid character corruption, especially with international content.
- Validate paths and permissions before writing to avoid runtime exceptions.
Flush Example
using (StreamWriter writer = new StreamWriter("realtime.log", true))
{
writer.WriteLine("Realtime event at " + DateTime.Now);
writer.Flush(); // Ensure it's written immediately
}
Conclusion
StreamWriter is one of the most efficient and flexible ways to write text files in C#. Whether you're generating logs, writing reports, or exporting data, it provides simple, clean APIs that are both powerful and easy to manage.
By following best practices—handling exceptions, using encoding wisely, and managing large outputs efficiently—you ensure your file-writing operations are safe, fast, and maintainable.
FAQs
1. Does StreamWriter overwrite files by default?
Yes. To append instead of overwrite, pass true
as the second argument to the constructor.
2. Can StreamWriter write binary files?
No. StreamWriter is for text only. Use BinaryWriter
for binary files.
3. How to check if the file already exists before writing?
Use File.Exists("filename")
to check existence before writing.
4. Is StreamWriter thread-safe?
No. For multithreaded writing, use locks or thread-safe patterns like queues.
5. Can I use StreamWriter with MemoryStream?
Yes, you can write to a MemoryStream using a StreamWriter, useful for in-memory file generation.
Post a Comment