C# FileStream Tutorial with Programming Example

In this chapter you will learn:
  • What is FileStream Class?
  • Methods and Properties of FileStream Class.
  • C# StreamWriter and C# StreamReader
  • Programming Examples

What is FileStream Class in C#?

FileStream Class is used to perform the basic operation of reading and writing operating system files. FileStream class helps in reading from, writing and closing files.

How to use FileStream Class in C#?

In order to use FileStream class you need to include System.IO namespace and then create FileStream Object to create a new file or open an existing file.

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

FileMode – It specifies how to operation system should open the file. It has following members  
  1. Append - Open the file if exist or create a new file. If file exists then place cursor at the end of the file.
  2. Create - It specifies operating system to create a new file. If file already exists then previous file will be overwritten.
  3. CreateNew - It create a new file and If file already exists then throw IOException.
  4. Open – Open existing file.
  5. Open or Create – Open existing file and if file not found then create new file.
  6. Truncate – Open an existing file and cut all the stored data. So the file size becomes 0.
FileAccess – It gives permission to file whether it will open Read, ReadWrite or Write mode. FileShare – It opens file with following share permission.
  1. Delete – Allows subsequent deleting of a file.
  2. Inheritable – It passes inheritance to child process.
  3. None – It declines sharing of the current files.
  4. Read- It allows subsequent opening of the file for reading.
  5. ReadWrite – It allows subsequent opening of the file for reading or writing.
  6. Write – Allows subsequent opening of the file for writing.

Programming Example

In this programming Example we will create a new file "CsharpFile.txt" and saves it on disk. And then we will open this file, saves some text in it and then close this file.

Create a blank .txt File using FileStream

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

namespace FileStream_CreateFile
{
    class Program
    {
        static void Main(string[] args)
        {                           
                FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Create);                
                fs.Close();
                Console.Write("File has been created and the Path is D:\\csharpfile.txt");
                Console.ReadKey();
        }
    }
}

Output
File has been created and the Path is D:\\csharpfile.txt
_
Explanation:

In the above program I added System.IO namespace so that I could use FileStream class in my program. Then I created an object of FileStream class fs to create a new csharpfile.txt in D drive.

Open csharpfile.txt and write some text in it

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

namespace AccessFile
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new FileStream("D:\\csharpfile.txt", FileMode.Append);
            byte[] bdata=Encoding.Default.GetBytes("Hello File Handling!");
            fs.Write(bdata, 0, bdata.Length);
            fs.Close();
            Console.WriteLine("Successfully saved file with data : Hello File Handling!");
            Console.ReadKey();
        }
    }
}

Output
Successfully saved file with data : Hello File Handling!
_
Explanation

In the above program again I created object as fs of FileStrem class. Then Encoded a string into bytes and kept into byte[] variable bdata and finally using Write() method of FileStream stored string into file.

Read data from csharpfile.txt File

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

namespace FileStream_ReadFile
{
    class Program
    {
        static void Main(string[] args)
        {
            string data;
            FileStream fsSource = new FileStream("D:\\csharpfile.txt", FileMode.Open, FileAccess.Read);
            using (StreamReader sr = new StreamReader(fsSource))
            {
                data = sr.ReadToEnd();
            }
            Console.WriteLine(data);
            Console.ReadLine();
        }
    }
}

Output
Hello File Handling!
_
Explanation

In the above example I opened file in a Read permission and use StreamReader class to read file.

Summary

In this chapter you have learned FileStream Class with detailed and complete described programming example. In the next chapter you will learn about StreamWriter Class.

 

Share your thought