Home > C# > C# Write To File

C# write to file

While working with different programs in c#. you may have come across the need of storing the data in a file on your computer’s directory. Because the data that we use on the console only lasts before closing the console or we can say that unless we stop the application. Data which we store in the file lasts as long as the file exists in the directory or someone explicitly erases the data from the file. This data in the file can be helpful for further use. C# allows us this functionality to read from and write to a file. C# reading from a file and C# write to file are two different tasks though they are interrelated in a way that the working of both these tasks is almost same. One is used to read data from the file while other write data to the file.

System.IO namespace

The C# System.IO namespace provides a number of classes that help us in performing various tasks with the files. These include reading from and writing to a file in c#, creating and deleting a file, opening and closing the file etc. The commonly used classes of System.IO namespace includes

  • 1- BinaryReader
  • 2- BinaryWriter
  • 3- BufferedStream
  • 4- Directory
  • 5- DirectoryInfo
  • 6- DriveInfo
  • 7- File
  • 8- FileInfo
  • 9- FileStream
  • 10- MemoryStream
  • 11- Path
  • 12- StreamReader
  • 13- StreamWriter
  • 14- StringReader
  • 15- StringWriter

 

Using File Class

Let’s have a look at this very basic example of C# write to file.  This below program is having an array of strings. And we use WriteAllLines function of File class from System.IO namespace. This function takes two arguments 1st the exact path of the file in the system and 2nd is an array of string literals. It writes each string in a separate line in the file.  We do not need to explicitly close or flush the file.  WriteAllLines function does this for us.

using System;

namespace filing
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lines = { "This is the First line.", "This is the Second line.", "This is the Third line." };
            System.IO.File.WriteAllLines(@"path to the file", lines);
        }
    }
}

What if we don’t want to write an array of strings instead we only have a single string available. We can write it to a file using the WriteAllText function of File class from System.IO namespace. It also takes two arguments 1st the exact path of the file in the system and 2nd is a string literal which we want to write in the file. Just like WriteAllLines it also closes the file after writing to it.

using System;
namespace filing
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "This is a string written to the file using WriteAllText function";
            System.IO.File.WriteAllText(@"path to the file",  text);        }
    }
}

Using StreamReader Class

Here is another way of writing to a file in c#.

using System;
using System.IO;

namespace filing
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamWriter writer =
            new StreamWriter("example.txt"))
            {
                writer.Write("1st  ");
                writer.WriteLine("2nd ");
                writer.WriteLine("Third");
            }
        }
    }
}

This above example uses StreamWriter class of System.IO namespace. We are using two different functions of this class to write to a file. The Write function writes in a file and places the cursor at the end of the same line while WriteLine function writes in the file and places the cursor at the start of the new line.

Note: – All the above examples write the file from scratch i.e. each time we run these programs old data from the files is removed and new data is written in the files.

Here is the simple program to keep the old data and write new data in the file.

using System;
using System.IO;

namespace filing
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamWriter writer =
            new StreamWriter("example.txt",true))
            {
                writer.WriteLine("This will not delete previous data");
            }
        }
    }
}

Some other options for writing to the file. i.e. asynchronously writing to a text file using StreamWriter class. We invoke WriteAsync function of StreamWriter class.

using System;
using System.IO;

namespace filing
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamWriter writer =
            new StreamWriter("example.txt",true))
            {
                writer.WriteAsync( "Writing asynchronously ");
            }
        }
    }
}

File class provides AppenAllLines function to append lines to the already existing data in the file.

C# write to file using FileStream class

The Filestream class of the System.IO namespace also provides the facility of reading from and writing to the file in c#. To work with this class we create an object of it. It follows the following syntax to create its object.

FileStream <object_name> = new FileStream( <fileName>,
<FileMode Enumerator>,<FileAccess Enumerator>, <FileShare Enumerator>);

e.g.

FileStream file =  new FileStream(“example.txt”, FileMode.Open, 
FileAccess.Read, FileShare.Read);

FileMode can be any one of the followings

  • 1- Append
  • 2- Create
  • 3- CreateNew
  • 4- Open
  • 5- OpenOrCreate
  • 6- Truncate

FileAccess grants the access rights. i.e. You are opening the file for what purpose. It can be either Read, Write or both(ReadWrite).

FileShare enumerators have the following members

  • 1- Inheritable
  • 2- None
  • 3- Read
  • 4- ReadWrite
  • 5- Write
using System;
using System.IO;

namespace filing
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream File = new FileStream("example.dat", 
            FileMode.OpenOrCreate, FileAccess.ReadWrite);
            for (int i = 1; i <= 20; i++)
            {
                File.WriteByte((byte)i);
            }
            File.Position = 0;
            for (int i = 0; i <= 20; i++)
            {
                Console.Write(File.ReadByte() + " ");
            }
            File.Close();
            Console.ReadKey();
        }
    }
}

C# write to file using FileStram

 

 

 

Note: – FileStream read from and write to the file in the form of Bytes.

One thought on “C# Write To File

  1. Blogs are not just for socializing with others but it can also give us useful information. like this just like me I’am a new blogger and this article gave me lots of ideas on how to start blogging to a site or posts.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.