Home C# StreamWriter in C# tutorial

StreamWriter in C# tutorial

StreamWriter in C# is a class used for writing characters to a stream in a particular encoding.

It’s commonly used for working with text files and provides high-level, efficient methods for writing text data.

StreamWriter is a part of the System.IO namespace, and it is easier to use for text file operations compared to FileStream.

In this tutorial, we’ll cover:

1. Basics of StreamWriter

StreamWriter is used to write character data to a file. By default, it uses UTF-8 encoding, but you can specify different encodings if needed.

The class provides methods to write both individual lines of text and complete strings to a file.

Here’s how to create a basic StreamWriter object:

Syntax:

using System.IO;

// Create a StreamWriter instance to write to a file
using (StreamWriter writer = new StreamWriter("file.txt"))
{
    // Writing code goes here
}

The using statement ensures that the file is automatically closed and resources are released when you’re done writing.

2. Writing to a Text File with StreamWriter

To write data to a text file, use methods like Write() and WriteLine() to write text to the file.

Write() does not add a newline at the end, while WriteLine() does.

Example: Writing to a Text File

using System;
using System.IO;

public class StreamWriterWriteExample
{
    public static void Main()
    {
        using (StreamWriter writer = new StreamWriter("output.txt"))
        {
            writer.WriteLine("Hello, StreamWriter!");
            writer.Write("This is a line without a newline.");
            writer.WriteLine("This is a new line with WriteLine.");
            Console.WriteLine("Data written to file.");
        }
    }
}

Explanation:

  • WriteLine() writes text followed by a newline character.
  • Write() writes text without adding a newline.
  • The StreamWriter object automatically closes at the end of the using block, ensuring that resources are released.

Content in output.txt:

Hello, StreamWriter!
This is a line without a newline.This is a new line with WriteLine.

3. Appending to a Text File with StreamWriter

To add more data to an existing file without overwriting it, open the file in append mode using StreamWriter with the append parameter set to true.

Example: Appending to a Text File

using System;
using System.IO;

public class StreamWriterAppendExample
{
    public static void Main()
    {
        using (StreamWriter writer = new StreamWriter("output.txt", true))
        {
            writer.WriteLine("This is an appended line.");
            writer.WriteLine("Another line added at the end.");
            Console.WriteLine("Data appended to file.");
        }
    }
}

Explanation:

  • The StreamWriter constructor has an optional second parameter, append, set to true here, allowing data to be added to the end of the file.
  • If append is false (or omitted), the file contents will be overwritten.

Appended content in output.txt:

Hello, StreamWriter!
This is a line without a newline.This is a new line with WriteLine.
This is an appended line.
Another line added at the end.

4. Using StreamWriter with Different Encodings

By default, StreamWriter uses UTF-8 encoding, but you can specify different encodings, such as Unicode, ASCII, or UTF-32. To set a custom encoding, pass an Encoding object as a parameter.

Example: Writing with Different Encodings

using System;
using System.IO;
using System.Text;

public class StreamWriterEncodingExample
{
    public static void Main()
    {
        string data = "This is some text with UTF-32 encoding.";

        using (StreamWriter writer = new StreamWriter("utf32_output.txt", false, Encoding.UTF32))
        {
            writer.WriteLine(data);
            Console.WriteLine("Data written with UTF-32 encoding.");
        }
    }
}

Explanation:

  • Encoding.UTF32 specifies UTF-32 encoding.
  • The file utf32_output.txt is written using UTF-32, which supports a wide range of characters.

Output in utf32_output.txt:

This is some text with UTF-32 encoding.

5. Practical Example: Logging Data with StreamWriter

A common use of StreamWriter is logging information to a file. Here’s an example where we write logs with timestamps, appending each new entry.

Example: Logging Data with Timestamps

using System;
using System.IO;

public class Logger
{
    private string logFilePath;

    public Logger(string logFilePath)
    {
        this.logFilePath = logFilePath;
    }

    public void LogMessage(string message)
    {
        using (StreamWriter writer = new StreamWriter(logFilePath, true))
        {
            string logEntry = $"{DateTime.Now}: {message}";
            writer.WriteLine(logEntry);
            Console.WriteLine("Log entry added: " + logEntry);
        }
    }
}

public class LogExample
{
    public static void Main()
    {
        Logger logger = new Logger("log.txt");
        logger.LogMessage("Application started.");
        logger.LogMessage("Application running smoothly.");
        logger.LogMessage("Application terminated.");
    }
}

Explanation:

  • The Logger class has a LogMessage method that adds a message with a timestamp.
  • DateTime.Now provides the current date and time, which is added to each log entry.
  • The StreamWriter opens in append mode, so each new log entry is added at the end of log.txt.

Sample content in log.txt:

2024-10-29 14:00:00: Application started.
2024-10-29 14:05:30: Application running smoothly.
2024-10-29 14:10:00: Application terminated.

Advanced Example: Writing Structured Data to a File

Using StreamWriter, we can format data for structured output, such as CSV files.

Example: Writing a CSV File

using System;
using System.IO;

public class CsvWriter
{
    public void WriteDataToCsv(string filePath)
    {
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            // Writing CSV headers
            writer.WriteLine("ID,Name,Age");

            // Writing data rows
            writer.WriteLine("1,John Doe,30");
            writer.WriteLine("2,Jane Smith,25");
            writer.WriteLine("3,Bob Johnson,35");

            Console.WriteLine("CSV data written to file.");
        }
    }
}

public class CsvExample
{
    public static void Main()
    {
        CsvWriter csvWriter = new CsvWriter();
        csvWriter.WriteDataToCsv("data.csv");
    }
}

Explanation:

  • The WriteDataToCsv method writes column headers and data rows in CSV format.
  • StreamWriter writes each line as a row in the CSV file.

Content in data.csv:

ID,Name,Age
1,John Doe,30
2,Jane Smith,25
3,Bob Johnson,35

Summary

StreamWriter is an excellent tool for writing text data to files in C#, making it ideal for logging, structured data storage, and character-based file operations.

Here’s a recap of the main points:

  • Basic Setup: Use StreamWriter with using statements to ensure proper resource management.
  • Writing to a File: WriteLine() adds a newline, and Write() does not, giving flexibility in formatting.
  • Appending Data: Open StreamWriter in append mode to add data to an existing file.
  • Using Different Encodings: Specify custom encodings like UTF-32 or ASCII as needed.
  • Logging with Timestamps: StreamWriter is ideal for logging, with timestamped entries for tracking events.
  • Structured Data: Format data as CSV or similar structured formats for easy data storage.

StreamWriter simplifies working with text files, offering efficient, high-level methods for writing text while supporting various encoding and formatting needs.

You may also like