How to write file in C# using StreamWriter

 Posted on 08/30/2019

Share On: facebook gplus twitter

To write data in file, StreamWriter class in C# writes characters to a stream in encoding. There is a method called "StreamWriter.Write" is used to write data to a stream in C#.

Here, base class is TextWriter and StreamWriter class is inherited from it which provides methods to write an object to a string, write text to a file, or to serialize XML data.

You must have to include namespace called "System.IO" in your asp.net application to use StreamWriter class and its methods.

Lets look into a different options how you can write data into a file using StreamWriter class.

1. WriteLine - This will write one line data or text string everytime when method called to write into a file.
2. Write - This will writes data to the stream into a file.
3. WriteAsync - This will writes data to the stream asynchronously into a file.
4. WriteLineAsync - This will writes one line to the text string or stream asynchronously into a file.

Here, StreamWriter constructor takes a filename or a FileStream object with Encoding, and buffer size as optional parameters to write date into a specified file.

StreamWriter using a FileStream

Lets create an object from FileStream by passing few parameters.

string strFileName = @"C:\SampleApplication\TestFile.txt";
FileStream flStream = new FileStream(strFileName, FileMode.CreateNew);

StreamWriter constructor will use a FileStream object with Encoding, and buffer size as optional parameters. The below sample code will creates a StreamWriter from a FileStream with default encoding and buffer size.

using (StreamWriter sWriter = new StreamWriter(fStream))
{
  writer.WriteLine("Sample file write in asp.net");
}

Method 1 - StreamWriter.WriteLine()

using (StreamWriter sWriter = new StreamWriter(fStream, Encoding.UTF8))
{
  swriter.WriteLine("Sample text line 1");
  swriter.WriteLine("Sample text line 2");
  swriter.WriteLine("Sample text line 3");
}

Here, "WriteLine()" method is used to write a text or string to the next line to the stream. As method name indicates, it always create a new line and write text in line. You can write as much as lines you want by defining it everytime as displayed in above example.

Method 2 - StreamWriter.Write()

using (StreamWriter swriter = new StreamWriter(fStream, Encoding.UTF8))
{  
  swriter.Write("This is a sample test data to write into file");
}

Here, "Write()" method is used to write different type of data like a char, string or text, or a string to the steam.

Method 3 - StreamWriter.WriteAsync()

UnicodeEncoding unicodeencoding = new UnicodeEncoding();
string strText = "Hello, this is a write async method sample";
char[] chars = unicodeencoding.GetChars(unicodeencoding.GetBytes(strText));
using (StreamWriter swriter = File.CreateText(@"C:\SampleApplication\TestFile.txt"))
{
  await swriter.WriteAsync(chars, 0, chars.Length);
}

Here, "WriteAsync()" method is used to write a char, string of chars, or a string to the stream asynchronously. This method basically returns a Task which represents the asynchronous write operation to write a data into file.

Method 4 - StreamWriter.WriteLineAsync()

using (StreamWriter swriter = File.CreateText(@"C:\SampleApplication\TestFile.txt"))
{
 await swriter.WriteLineAsync('I');
 await swriter.WriteLineAsync('N');
 await swriter.WriteLineAsync('D');
 await swriter.WriteLineAsync('I');
 await swriter.WriteLineAsync('A');
}

Here, "WriteLineAsync()" method it used to write a char or an array to a new asynchronously. This method basically returns a Task which represents the asynchronous write operation to write a data into file. The above example will show how to write a new line for each character to the stresm.

Example to write a text into the file and display in console application output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace SampleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string strFileName = @"C:\SampleApplication\TestFile.txt";
                FileStream fStream = new FileStream(strFileName, FileMode.CreateNew);

                using (StreamWriter sWriter = new StreamWriter(fStream, Encoding.UTF8))
                {
                    sWriter.WriteLine("Sample text line 1");
                    sWriter.WriteLine("Sample text line 2");
                    sWriter.WriteLine("Sample text line 3");
                }
            }
            catch (Exception Ex)
            {
                Console.Write(Ex.Message.ToString());
            }
        }
    }
}

OUTPUT:

hot to write file in C#

Add Comment: