Advertisement



< Prev
Next >



C# FileStream



The FileStream class is used to create a byte stream, which is used to write or read bytes to/from a file. The FileStream class is defined in the System.IO namespace.




Constructors of FileStream


Constructors Description
FileStream(String path, FileMode mode)
This constructor creates an object of FileStream class with the specified path and creation mode for the file that will be encapsulated within the current FileStream object.

FileStream(String path, FileMode mode, FileAccess permission)
The constructor creates an object of the FileStream class with the specified path, creation mode, and read/write permission for the file.






Some commonly used method of FileStream


Methods Description
int ReadByte()
This method reads one byte from this byte stream and returns the successfully read byte.

int Read(byte[] array, int index int count)
This method reads a block of bytes from the stream and writes the data in a buffer i.e. an array of bytes, where:
  • index, represents the index position in array at which the read bytes will be placed.
  • count, represents the maximum number of bytes to read.
The method returns the total number of bytes read.

void Write()
This method write one byte to the current position in the byte stream.

void Write(byte[] array, int index int count)
This method writes a block of bytes from an array to the stream, where:
  • index, represents the starting index position in array from which the bytes will be read to write to the stream.
  • count, represents the maximum number of bytes to write.


int Seek(int offset, SeekOrigin origin)
This method sets the current position of the file pointer, where:
  • offset, represents the point relative to origin from which to begin seeking.
  • origin, represents the beginning, the end, or the current position as a reference point for offset, using a value of type SeekOrigin.
This method returns the new position of the file pointer in the stream.

void Flush()
This method closes this byte stream and also frees any resources connected with this stream.

void Close()
This method closes this byte stream and also frees any resources connected with this stream.






We are reading an existing file(which has permissions to read and write to it) called "TextBook1.txt", by using its path "D:\\TextBook1.txt". Let's say the contents of this file -

TextBook1.txt
World peace is extremely important. 


Note: We will use the FileMode field FileMode.Open to open the existing file(which has permissions to read and write to it) to read or write bytes to it(depending on whether you call the read or write methods of the stream class) and in this case, we will just read.

//Program to read one byte at a time through an existing file using FileStream.

using System;
using System.IO;

class A
{
public static void Main(String[] ar)
{
	try
	{
		//Creating an object of FileStream
		FileStream fs = new FileStream("D:\\Textbook1.txt", FileMode.Open);
	
		int c;
	
	
		//Calling the ReadByte() method to reading one byte out of a file
		Console.WriteLine("Reading the contents of a file: ");
		while((c = fs.ReadByte()) !=-1) 
		{
			//Casting byte to char for displaying the read character on the screen
			Console.Write((char)c); 
		}

		//Closing the byte stream i.e. FileStream
		fs.Close();
	}
	catch(IOException e)
	{
		Console.WriteLine(e);
	}

}
}


Output is -:


World peace is extremely important


Program Analysis





Advertisement





In this example, we are reading an existing read-only file, but this time we are reading a whole byte array at once for faster reading by calling the Read(byte[] b, int index, int count) method.

Note: As we are reading a read-only file, so we cannot just use the FileMode field FileMode.Open which opens the existing file to not just read but also write data to it, while we want to read from a read-only file, therefore, we will call a different constructor of FileStream class that takes a FileAccess field and we will use the FileAccess.Read, to specify that we just want to read data from the file and not write to it, hence, allowing us to read from a read-only file.

//C# Program to read a byte array out of an existing file using FileInputStream.
 
using System;
using System.IO;
using System.Text;

class A
{
public static void Main(String[] ar)
{
	try
	{
		//Creating an object to FileStream and using FileMode.Open	
		//And, FileAccess.Read, to read a read-only file
		FileStream fs = new FileStream("D:\\TextBook2.txt", FileMode.Open, FileAccess.Read);
	
		//Total number of bytes in the file to read
		int num =(int)fs.Length;

		//Printing the total number of bytes to read	
		Console.WriteLine("Number of bytes available to read =" + num);
	
	
		//Creating a byte array with size equal to the number of bytes to read
		byte[] b = new byte[num];
	
		int c;
	
		//Read() method stops reading from file when EOF is reached i.e. -1	
		if( (c = fs.Read(b, 0, b.Length)) != -1) 
			Console.WriteLine("Number of bytes read = " + c);

		//Creating a String from the byte array
		String s = Encoding.UTF8.GetString(b, 0, b.Length);  

		//Printing the contents of the file read
		Console.WriteLine("The contents of the read-only file: " +  s);

		//Closing the byte stream i.e. FileStream		
		fs.Close();
	}
	catch(IOException e)
	{
		Console.WriteLine(e);
	}
}
}


Output is -:


Number of bytes available to read =36
Number of bytes read = 36
The contents of the read-only file: World peace is extremely important.


Program Analysis






  • Write one byte at a time to a file using WriteByte() method.


  • In this example, we are writing a byte at a time to a new file called TextBook3.txt, by passing its full path D:\\TextBook3.txt to the constructor of FileStream. First, the file is created and then byte(one at a time) is written to it.

    Note: We will use the FileMode field FileMode.OpenOrCreate to create the new file and write bytes to it.

    //C# A program to write one byte at a time to a file using FileOutputStream. 
    
    using System;
    using System.IO;
    using System.Text;
    
    class A
    {
    public static void Main(String[] ar)
    {
    	try
    	{
    		//Creating a String object 
    		String str = "Keep smiling and think positive.";
    	
    		//Creating a byte array from a String
    		byte[] bA = Encoding.ASCII.GetBytes(str);  
    
    		//Creating an object of FileStream to write to a file
    		//We are going to use the FileMode OpenOrCreate to create a new file to write to it
    		FileStream fs = new FileStream("D:\\TextBook2.txt", FileMode.OpenOrCreate);
    		foreach(byte bt in bA)
    		{
    			//writing one byte at a time to the file.
    			fs.WriteByte(bt);	
    		}
    	
    		fs.Flush();
    		fs.Close();
    	}
    	catch(IOException e)
    	{
    		Console.WriteLine(e);
    	}
    }
    }
    


    Output is -:


    A file called "TextBook2.txt" is created in D: drive, with the contents -:
    Keep smiling and think positive.


    Program Analysis





    Advertisement





    In this example, we are writing to an existing write-only file, to write a whole byte array(at once) to it. This performs faster writing, because writing a whole byte array at once is faster than writing one byte at a time.

    Note: As we are writing to a write-only file, so we cannot just use the FileMode field FileMode.Open which opens the existing file to not just write data to it but also read from it, while we want to write to a write-only file, therefore, we will call a different constructor of FileStream class that takes a FileAccess field and we will use the FileAccess.Write, to specify that we just want to write date to the file and not read and allows us to write to a write-only file.

    //C# A program to write a byte array to a file using FileStream. 
    
    using System;
    using System.IO;
    using System.Text;
    
    class A
    {
    public static void Main(String[] ar)
    {
    	try
    	{
    	//Creating a String 
    	String str = "Always look at the bright side of life!";
    
    	//Creating a byte array from a String
    	byte[] bA = Encoding.ASCII.GetBytes(str);
    
    	//Creating an object of FileStream to write bytes to a file
    	//We are going to use the FileMode OpenOrCreate to create a new file
    	//And FileAccess Write mode to write bytes to a file.
    	FileStream fs = new FileStream("D:\\Book1.txt", FileMode.OpenOrCreate, FileAccess.Write);
    	
    	//Calling the Write(byte[] array, int index, int count) method 
    	//to write all the contents of byte array to the file
    	fs.Write(bA, 0, bA.Length);
    
    	//Calling the Flush() method to flush all the buffered bytes from the FileStream
    	fs.Flush();
    
    	//Calling the Close() method to close the FileStream
    	fs.Close();
    	}
    	catch(IOException e)
    	{
    		Console.WriteLine(e);
    	}
    }
    }
     


    Output is -:


    A file called "Book1.txt" is created in D: drive, with the contents -:
    Always look at the bright side of life!


    Program Analysis






  • Calling the Seek() method of FileStream class.


  • In this example, we are writing a byte at a time to a new file by passing its full path to the constructor of FileStream. First, the file is created and then we will perform the following operations:

    Note: We will use the FileMode field FileMode.Create which creates a new file and any existing file with the same name is overwritten.

    //C# calling the Seek() method of FileStream class to first write to a file and to read from it.
    
    using System;
    using System.IO;
    using System.Text;
    
    
    class A
    {
    public static void Main(String[] ar)
    {
    	try
    	{
    		//Creating an object of FileStream
    		FileStream fs = new FileStream("D:\\Textbook8.txt", FileMode.Create);
    	
    		//Creating a String object 
    		String str = "There is a light at the end of the tunnel, so keep fighting!.";
    	
    		//Creating a byte array from a String
    		byte[] bA = Encoding.ASCII.GetBytes(str);  
    
    		Console.WriteLine("Writing to a file");
    		foreach(byte bt in bA)
    		{
    			//writing one byte at a time to the file.
    			fs.WriteByte(bt);	
    		}
    	
    		//Flushing the buffered date to the file
    		fs.Flush();
    
    		//Calling the Seek() method to set the file pointer to the beginning of the file
    		fs.Seek(0, SeekOrigin.Begin);
    
    		int c;
    	
    	
    		//Calling the ReadByte() method to reading one byte out of a file
    		Console.WriteLine("Reading the contents of the same file: ");
    		while((c = fs.ReadByte()) !=-1) 
    		{
    			//Casting byte to char for displaying the read character on the screen
    			Console.Write((char)c); 
    		}
    
    		//Closing the byte stream i.e. FileStream
    		fs.Close();	
    	}
    	catch(IOException e)
    	{
    		Console.WriteLine(e);
    	}
    
    }
    }
     


    Output is -:


    Writing to a file
    Reading the contents of the same file:
    There is a light at the end of the tunnel, so keep fighting!.






    Please share this article -




    < Prev
    Next >
    < C# User Defined Exception
    C# FileMode and FileAccess >



    Advertisement

    Please Subscribe

    Please subscribe to our social media channels for daily updates.


    Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




    Advertisement



    Notifications



    Please check our latest addition

    C#, PYTHON and DJANGO


    Advertisement