I/O in C#

Streams

For reading or writing any data, you need some device. This device is called as stream. A stream is an abstract image of a serial device. For better understanding just re-think, where you writes your important information (data). It is different types of files, disk, network channel or something that is able to reading, writing, or both in sequential manner. The actual destination/source of the stream can be hidden in stream concept. Stream is a base class for all other stream classes represents a byte stream. Stream is an abstract class.

The System.IO namespace contains important classes for reading and writing the data with files. These classes are used to navigate and manipulate files, directories, and drives.

Important classes for reading and writing the data with files are as follows:

ClassesDescription
FileProvides the basic functionality for reading and writing.
DirectoryUsed copying, moving, renaming, creating, and deleting directories.
PathPath class methods enables you to determine the location of file or directory
FileInfoMainly used for access and manipulating the files.
DirectoryInfoIt provides the information about the particular directory.
FileSystemInfoIt represents either a file or a directory.
FileStreamProvides read, write facility to the files.
StreamReaderIt is used to read data from files.
StreamWriterIt enables you to write data to file.
FileSystemWatcheIt monitors changes to subdirectories and files within the specified directory.

The FileInfo Class

FileInfo class is used for operations such as copying, moving, renaming, creating, opening, and deleting, files. It means that it is mainly used for access and manipulating the files.

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo myFile = new FileInfo(@"c:\myDataFile.txt");           
            if (myFile.Exists)
            {
                Console.WriteLine ("Filename : {0}", myFile.Name);
                Console.WriteLine ("Path : {0}", myFile.FullName);
                Console.WriteLine ("DirectoryName : {0}", myFile.DirectoryName);
                Console.WriteLine ("Length : {0}", myFile.Length);
                myFile.CopyTo (@"D:\myDataFile.txt");
            }            
            Console.ReadLine();
        }
    }
}


In the above example, Name, FullName, DirectoryName and Length property of FileInfo class is used. Name property gets the name of file. FullName provides the full path of file or directory. DirecotryName property provides the name of the directory. Length property gets the size in bytes of the file.

Let us take one example that will discuss some important method of FileInfo class.

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
             // Create Method is used to create file.
            FileInfo myFile = new FileInfo(@"c:\myDataFile.txt");
            FileStream fs = myFile.Create();
            Console.WriteLine("File has been created");    
            // CreateText Method
            FileInfo fileObj = new FileInfo(@"D:\FileWithText.txt");
            StreamWriter str = fileObj.CreateText();
            str.WriteLine("Welcome at TutorialRide");
            Console.WriteLine("File has been created with text");
            str.Close();         
           // Delete Method of FileInfo class is used to delete file.
            if (fileObj.Exists)
            {
                fileObj.Delete();
                Console.WriteLine("File has been deleted");
            }        
            // MoveTo Method
            string path = @"C:\FileWithText.txt";
            if (fileObj.Exists)
            {
                fileObj.MoveTo(path);
                Console.WriteLine("File moved to {0}.", path);
            }

           //Please keep in mind, if the file with same name is already exist in
          //designated path, then it will through the exception.
          // ApendText Method
            FileInfo fi = new FileInfo(@"D:\NewFile.txt");
            StreamWriter swObj = fi.AppendText();
            if (fi.Exists)
            {
                swObj.WriteLine("Welcome");
                swObj.WriteLine("at");
                swObj.WriteLine("TutorialRide");
                Console.WriteLine("File has been appended");
                swObj.Close();
            }           
           //Use of Opentext Method        
            StreamReader readerObj = fi.OpenText();
            string str = "";
            while ((str = readerObj.ReadLine()) != null)
            {
                Console.WriteLine(str);
            }                   
            Console.ReadLine();
        }
    }
}


Create method
Create method of FileInfo class will create a file at given path. If the file is already exists, then it will overwrite all the content. If the file is not available, then it will create a new file at designated place in your computer. You will loss all the previous data if you use create method. Return type of Create() method is FileStream object. We will discuss FileStream class in detail in next section.

CreatText() method
CreatText() method works same as Create() method, but the main difference is that you can write text in the file with this method. CreatText() method returns the StreamWriter object.

move() method
If the file is exists, move() method moves the file to designated path. It is same as cut and copy command.

AppendText() method
AppendText() method of FileInfo class will append the text in the file with the help of StreamWriter class.

The DirectoryInfo Class

As its name indicates, it provides the information about the particular directory.

Important properties of DirectoryInfo class

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo myDir = new DirectoryInfo(@"c:\windows");
            Console.WriteLine("FullName: {0}", myDir.FullName);
            Console.WriteLine("Name: {0}", myDir.Name);
            Console.WriteLine("CreationTime: {0}", myDir.CreationTime);
            Console.WriteLine("LastAccessTime: {0}", myDir.LastAccessTime);
            Console.WriteLine("LastWriteTime: {0}", myDir.LastWriteTime);
            Console.WriteLine("Root: {0}", myDir.Root);
            Console.ReadLine();
        }
    }
}


In the above example, Name, FullName, CreationTime, LastAccessTime, LastWriteTime, and Root property of DirectoryInfo class is used. Name property gets the name of directory. FullName provides the full path of file or directory. CreationTime property gets or sets the CreationTime of the current directory. LastAccessTime property gets the Last Access Time of Directory. Root gets the last portion of path.

Use of important method of DirectiveInfo class

If the same name directory is available, then it will give the run time exception. For handling the exception use proper error handling techniques.

There are two overload methods are available to delete the directory. If the directory is empty then use Delete () method without any parameter and, if the directory has file or sub- directory then use Delete (true) method.

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create Method
            String path = @"D:\MyDirectory";
            DirectoryInfo dirObj = new DirectoryInfo(path);
            dirObj.Create();
            if (dirObj.Exists)
            {
                Console.WriteLine("Directory has been created");
            }

            // CreateSubdirectory Method           
            dirObj.CreateSubdirectory("MySubDirectory");
            Console.WriteLine("Sub Directory has been created");    
            // MoveTo Method        
            dirObj.MoveTo(@"D:\MyNewDirectory");           
             Console.WriteLine("Directory has been Moved within drive");  
            // you can move directive in same drive
            //// Delete Method
             if (dirObj.Exists)
             {
                 dirObj.Delete();
                 Console.WriteLine("Directory has been deleted");
             }            
            // Get directories and files in particular Folder.
             dirObj = new DirectoryInfo(@"C:\WINDOWS");
             foreach (FileInfo file in dirObj.GetFiles())
             {
                 Console.WriteLine("File: {0}", file.Name);
             }
             Console.WriteLine("\n=======================================\n");
             foreach (DirectoryInfo file in dirObj.GetDirectories())
             {
                 Console.WriteLine("Direcotory: {0}", file.Name);
             }
            Console.ReadLine();
        }
    }
}

The StreamWriter Object

The StreamWriter class enables you to write data to a file. StreamWriter class has seven different constructors, which you can use according to your need.

StreamWriter object can be created in different ways.
If you have FileStream object, then you can initialize StremWriter object as given below.

FileStream fileStream = new FileStream("MyFile.txt",FileMode.CreateNew);
StreamWriter sw = new StreamWriter(fileStream);


FileStream constructor has FileMode parameter that decides which type of operation you can perform with file. FileMode is an enumerator that has the following value.

FileModeDescription
CreateNewIt creates the new file.
AppendOpens the file if exists, if not create new file and append the text.
CreateCreates the new file, if file exists it will be overwritten.
OpenIt is used for open an existing file.
OpenOrCreateOpens the file if exits otherwise it creates new file.
TruncateIt is used to truncate the content.

You can also create StreamWriter object directly.

StreamWriter sw = new StreamWriter("MyFile.txt ", true);

The constructor of StreamWriter takes two parameters. First parameter is the name of file and second is a Boolean value that specifies whether to append the text to the file or create a new one. If you set second parameter as false, then a new file will create or the existing file is truncated.

If it is set to true, then new file will be created, if file is not present. If file is already present, then data will be appended.

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = null;
            try
            {
                FileStream fileStream = new FileStream(@"D:\MyFile.txt", FileMode.OpenOrCreate);
                sw = new StreamWriter(fileStream);
                // Write data to file.
                sw.WriteLine("Welcome at TutorialRide.");
                sw.Write("C# is fun.");
            }
            catch (IOException e)
            {
                Console.WriteLine("An IO exception has occured!");
                Console.WriteLine(e.Message);
            }
            finally
            {
                sw.Close();
            }
            Console.ReadLine();
        }
    }
}

The StreamReader Object

StreamReader class is used to read data from files. Like StreamWriter class, you can also initialize StreamReader in different ways.

FileStream fileStream = new FileStream("MyFile.txt", FileMode.Open);
StreamReader sr = new StreamReader(fileStream);


You can also initialize StreamReader object as given below.

StreamReader sr = new StreamReader("MyFile.txt ", true);

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str;
            FileStream fileStream=null;
            StreamReader sr = null;
            try
            {
                fileStream = new FileStream(@"D:\MyFile.txt",FileMode.Open);
                sr = new StreamReader(fileStream);
                str = sr.ReadLine();
                // Read data in line by line.
                while (str != null)
                {
                    Console.WriteLine(str);
                    str = sr.ReadLine();
                }                
            }
            catch (IOException e)
            {
                Console.WriteLine("An IO exception has been occured!");
                Console.WriteLine(e.Message);               
            }
            finally
            {
                sr.Close();
            }
            Console.ReadLine();
        }
    }
}

File Class

File class provides the static method for creating, deleting, moving, coping and opening of files. You can also get or set file attribute by using File class. Open method of File class supports different enum.

The following table describes the enumerations.

EnumerationValue
FileModeCreate, CreateNew, Append, Open, OpenOrCreate, Truncate
FileAccessRead, Write, ReadWrite
FileShareRead, Write, ReadWrite,None, Delete, Truncate, Inheritable

Example

using System;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"D:\MyDataFile.txt";
            // Write information to the file.
            StreamWriter sw = File.CreateText(path);              
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome at TutorialRide");
            sw.Close();
            // Open the file to read.
            StreamReader sr = File.OpenText(path);            
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
                sr.Close();
            Console.ReadLine();
        }
    }
}

Writing and Reading Compressed Files

DeflateStream and GZipStream class are used compress and decompress the files from your code. These classes are available in System.IO.Compression. GZipStream class constructor takes two parameters. First parameter is the name of the file and second parameter is compression mode.

Compression mode is an enum that have two values.

1. CompressionMode.Compress
2. CompressionMode.Decompress

GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Compress);

GZipStream constructor performs the compression task. The above code instructs for compression of data and place in designated file. Decompression code is same as compression code but the slight change is in constructor as given below.

GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Decompress);

Use CompressionMode.Decompress in constructor in place of CompressionMode.Compress.

For compression and decompression, you can also use DeflateStream class. GZipStream include extra information that might be helpful to decompress a file. The compression stream classes can be used to compress or decompress any data up to 4 GB.

Example

using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleGZIPSTREAM
{
    class Program
    {
        static void SaveFile(string filename, string data)
        {
            FileStream fileStream =
            new FileStream(filename, FileMode.Create, FileAccess.Write);
            GZipStream zipStream =
            new GZipStream(fileStream, CompressionMode.Compress);
            StreamWriter sw = new StreamWriter(zipStream);
            sw.Write(data);
            sw.Close();
        }
        static string LoadCompressedFile(string filename)
        {
            FileStream fileStream =
            new FileStream(filename, FileMode.Open, FileAccess.Read);
            GZipStream zipStream =
            new GZipStream(fileStream, CompressionMode.Decompress);
            StreamReader sr = new StreamReader(zipStream);
            string data = sr.ReadToEnd();
            sr.Close();
            return data;
        }
        static void Main(string[] args)
        {            
            Console.WriteLine("Enter you information for compression");
            string str = Console.ReadLine();
            SaveFile(@"D:\MyDataFile.txt",str);
            string result = LoadCompressedFile(@"D:\MyDataFile.txt");
            Console.WriteLine(result);
            Console.ReadLine();
        }

    }
}


Run the above application, the savefile() method compress the information and save it in the given file. The LoadCompressedFile() method again decompress your information.