Monday, May 24, 2021

C# FileStream Class

Previous Topic: Stream

FileStream is a public class derived from Stream class in System.IO namespace. The FileStream class has non-static methods and properties and hence FileStream class members can be used after creating an instance of the FileStream class. FileStream class is used to open a file and thereby creating file stream so that the file can be read and write. It means that to manipulate a file, we should first create an instance of FileStream class. This instance is passed as argument to the constructor of StreamWriter and StreamReader classes.

You can use the Read, Write, CopyTo, and Flush methods to perform synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread.


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

namespace ConsoleFileStream
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"F:\Test1.txt";//verbatim literal to convert metacharcaters to simple characters
          
            //FileMode.Append=> Append data to the existing file
            //FileMode.Create=> Create a new file or overwrite the existing file
            //FileMode.CreateNew=>Create a new file but if throws exception if file exists
            //FileMode.Open=> Opens the existing file
            //FileMode.OpenOrCreate=>Open if file exists, else create file
            //FileMode.Truncate=>Open existing file and the file size becomes 0 bytes

            FileStream fstream = new FileStream(file, FileMode.Create);
            //Properties of FileStream object
            Console.WriteLine("CanRead: {0}", fstream.CanRead);
            Console.WriteLine("CanSeek: {0}", fstream.CanSeek);
            Console.WriteLine("CanWrite: {0}", fstream.CanWrite);
            Console.WriteLine("Is Asynchronous: {0}", fstream.IsAsync);
            /* 
             * The IsAsync property detects whether the file handle was opened asynchronously.You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter.
            */
            for (byte i = 65; i < 90; i++)
            {
                fstream.WriteByte(i); //Upper case 
                fstream.WriteByte(9);//Tab char
            }
            
            //get rid of used resource i.e. file handle
            //clean up the memory
            //fstream.Dispose(); //if Dispose, we cannot reopen the resource/file
            fstream.Close();// if Close, we can reopen the file
            
            string file2 = @"F:\Test2.txt";
            using(FileStream fs = new FileStream(file2, FileMode.Append))
            {
                string text = "I am learning FileStream class in C#.";
                byte[] data = Encoding.UTF8.GetBytes(text); //Encoding belongs to System.Text
                fs.Write(data, 0, text.Length);
            }
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment

Hot Topics