0
0
CsharpHow-ToBeginner · 3 min read

How to Use StreamWriter in C#: Simple Guide with Examples

Use StreamWriter in C# to write text to files by creating an instance with a file path, then calling Write or WriteLine methods. Always wrap it in a using block to ensure the file is properly closed after writing.
📐

Syntax

The basic syntax to use StreamWriter involves creating an instance with a file path, optionally specifying whether to append to the file. Use Write or WriteLine to write text, and close the writer to save changes.

  • StreamWriter(string path, bool append): Creates a writer for the file at path. If append is true, text is added to the end; otherwise, the file is overwritten.
  • Write(string text): Writes text without a new line.
  • WriteLine(string text): Writes text followed by a new line.
  • Use Dispose() or a using block to close the writer and release resources.
csharp
using System.IO;

// Create StreamWriter to write to a file
using (StreamWriter writer = new StreamWriter("example.txt", append: false))
{
    // Write text
    writer.WriteLine("Hello, world!");
}
💻

Example

This example shows how to write multiple lines to a file named output.txt using StreamWriter inside a using block. The using block ensures the file is closed automatically.

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "output.txt";

        using (StreamWriter writer = new StreamWriter(filePath, append: false))
        {
            writer.WriteLine("Line 1: Hello, StreamWriter!");
            writer.WriteLine("Line 2: Writing to a file is easy.");
            writer.WriteLine("Line 3: Goodbye!");
        }

        Console.WriteLine("Text written to 'output.txt'.");
    }
}
Output
Text written to 'output.txt'.
⚠️

Common Pitfalls

Common mistakes when using StreamWriter include:

  • Not closing the writer, which can cause data not to be saved.
  • Forgetting to use using blocks, leading to resource leaks.
  • Overwriting files unintentionally by not setting append to true when needed.
  • Trying to write to a file that is open in another program, causing exceptions.
csharp
/* Wrong way: Not closing the StreamWriter */
StreamWriter writer = new StreamWriter("file.txt");
writer.WriteLine("Hello");
// Forgot to call writer.Close() or dispose

/* Right way: Using 'using' block to auto-close */
using (StreamWriter writer = new StreamWriter("file.txt"))
{
    writer.WriteLine("Hello");
}
📊

Quick Reference

FeatureDescription
StreamWriter(string path, bool append)Creates a writer for the file; append controls overwrite or add.
Write(string text)Writes text without a newline.
WriteLine(string text)Writes text followed by a newline.
using statementEnsures the StreamWriter is closed and disposed automatically.
Close() or Dispose()Manually closes the writer and flushes data.

Key Takeaways

Always use a using block with StreamWriter to ensure the file is closed properly.
Set append to true if you want to add text to an existing file instead of overwriting it.
Use WriteLine to write text with a newline, and Write for text without a newline.
Not closing StreamWriter can cause data loss or file locks.
Handle exceptions when the file is in use or path is invalid.