StreamWriter Class in C# with Programming Example

In this chapter you will learn:
  • What is StreamWriter Class?
  • How to write text into a file using StreamWriter Class?
  • Programming Example

What is StreamWriter Class?

StreamWriter Class is more popular in File Handling and it is very helpful in writing text data in the file. It is easy to use and provides a complete set of constructors and methods to work.

How to write text into a file using StreamWriter Class?

It is very easy to writer data into a text file using StreamWriter Class and most of the beginners prefer to use this class in writing file. You can understand it with the following programming example.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace StreamWriter_Class
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\csharpfile.txt";
            using (StreamWriter writer = new StreamWriter(file))
            {
                writer.Write("Hello");
                writer.WriteLine("Hellow StreamWriter Class");
                writer.WriteLine("How are you!");
            }
            Console.WriteLine("Data Saved Successfully!");
            Console.ReadKey();
        }
    }
}

Now open D:\csharpfile.txt and you will see data is saved.

Save Variable data to file

Several times you need to save variable data in a file. These variable data might be the output of your program, log details, exception error etc. In the next programming, I will show you how can you save variable data in a file using StreamWriter Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace StreamWriter_VariableData
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\csharpfile.txt";
            int a, b, result;
            a = 5;
            b = 10;
            result = a + b;
            
            using (StreamWriter writer = new StreamWriter(file))
            {
                writer.Write("Sum of {0} + {1} = {2}", a, b, result);
            }
            Console.WriteLine("Saved");
            Console.ReadKey();
        }
    }
}

Now open the D:\csharpfile.txt again and you will see the following text in a file.

Sum of 5 + 10 = 15

Summary

In this chapter you learned StreamWriter Class and the way to use it in programming. The next chapter explains StreamReader Class in C#.

More Articles