C# File Handling Programming Examples and Practice Question

In this chapter you will learn:
  • C# File Handling with Programming Example
  • Practice Question and Their Answer.

This chapter is designed for learn C# File Handling with practice question and answer. Your understanding of File Handling will be enhanced more by reading this chapter.

Qu 1. Make a D:\csharp\example.txt file using following class and Read and Write Date and Time. You must make D:\csharp folder before executing this program otherwise it will throw DirectoryNotFound Exception.
  1. FileStream Class
  2. StreamWriter and StreamReader
  3. TextWriter and TextReader
 

Answer

FileStream

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

namespace Example1_FileStream
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string file = @"D:\csharp\example.txt";
                //Creating File
                FileStream fs = new FileStream(file, FileMode.Create);
                //Adding current date and time in file
                byte[] bdata = Encoding.Default.GetBytes(DateTime.Now.ToString());
                fs.Write(bdata, 0, bdata.Length);
                Console.WriteLine("Data Added");
                fs.Close();
                //Reading File
                string data;
                FileStream fsread = new FileStream(file, FileMode.Open, FileAccess.Read);
                using (StreamReader sr = new StreamReader(fsread))
                {
                    data = sr.ReadToEnd();
                }
                Console.WriteLine(data);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
            Console.ReadKey();
        }
    }
}

Output
Data Added
17-08-2016 AM 08:27:31
_

StreamWriter and StreamReader

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

namespace Example1_Stream
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\csharp\example.txt";
            //Creating and Writting
            using (StreamWriter writer = new StreamWriter(file))
            {                
                writer.Write(DateTime.Now.ToString());
                Console.WriteLine("Successfully Added Current Date and Time");
            }            
            //Reading File
            using (StreamReader reader = new StreamReader(file))
            {
                Console.Write("Reading Current Time : ");
                Console.WriteLine(reader.ReadToEnd());
            }
            Console.ReadKey();
        }
    }
}

Output
Successfully Added Current Date and Time
Reading Current Time : 17-08-2016 AM 08:29:00
_

TextWriter and TextReader

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

namespace Example1_Text
{
class Program
{
static void Main(string[] args)
{
string file = @"D:\csharp\example.txt";
//Writting File
using (TextWriter writer = File.CreateText(file))
{
writer.WriteLine(DateTime.Now.ToString());
Console.WriteLine("Successfully Added Current Date and Time");
}
//Reading File
using (TextReader reader = File.OpenText(file))
{
Console.Write("Reading Current Time : ");
Console.WriteLine(reader.ReadToEnd());
}
Console.ReadKey();
}
}
}

Output
Successfully Added Current Date and Time
Reading Current Time : 17-08-2016 AM 08:31:23
_
Qu 2. Make D:\csharp\example.dat file using BinaryWriter class, store current date and time and read that text using BinaryReader class.

Answer

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

namespace Example2_Binary
{
    class Program
    {
        static void Main(string[] args)
        {
            string [email protected]"D:\csharp\example.dat";
            using (BinaryWriter writer = new BinaryWriter(File.Open(file, FileMode.Create)))
            {
                writer.Write("Current Date and Time is : " + DateTime.Now.ToString());
                writer.Write(true);
            }
            using (BinaryReader reader = new BinaryReader(File.Open(file, FileMode.Open, FileAccess.Read)))
            {
                Console.WriteLine(reader.ReadString());
            }
            Console.ReadKey();
        }
    }
}

Output
Current Date and Time is : 17-08-2016 AM 08:33:45
_
Qu 3. Manipulate following string using StringWriter and StringReader class.
"I am reading File Handling at Complete C# Tutorial.com"

Answer

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

namespace Example3_String
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "I am reading \n File Handling at \n Complete C# Tutorial.com";
            //Writing string into StringBuilder
            StringBuilder sb = new StringBuilder();
            using (StringWriter writer = new StringWriter(sb))
            {
                //Store Data on StringBuilder
                writer.WriteLine(text);
                writer.Flush();
                writer.Close();
            }
            //Read Entry
            using (StringReader reader = new StringReader(sb.ToString()))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
            Console.ReadKey();
        }
    }
}

Output
I am reading
File Handling at
Complete C# Tutorial.com
_
Qu 4. Create a Directory D:\example and then create a file in it D:\example\test.txt and store "Hello File Handling" text in it. Then gather information of Directory and File and print them on console.

Answer

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

namespace example_directory
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateDirectory();
            CreateFile();
            Console.ReadKey();
        }

        static void CreateDirectory()
        {
            //Creating Directory
            DirectoryInfo dir = new DirectoryInfo("D:\\example");
            try
            {
                //Check If Directory Exists
                if (dir.Exists)
                {
                    Console.WriteLine("Directory Already Exists");
                    Console.WriteLine("Directory Name : " + dir.Name);
                    Console.WriteLine("Path : " + dir.FullName);
                    Console.WriteLine("Directory is created on : " + dir.CreationTime);
                    Console.WriteLine("Directory is Last Accessed on " + dir.LastAccessTime);
                }
                //Create New Directory
                else
                {
                    dir.Create();
                    Console.WriteLine("Directory Created Successfully. Information of Directory:");
                    Console.WriteLine("Directory Name : " + dir.Name);
                    Console.WriteLine("Path : " + dir.FullName);
                    Console.WriteLine("Directory is created on : " + dir.CreationTime);
                    Console.WriteLine("Directory is Last Accessed on " + dir.LastAccessTime);
                }                
            }
            catch (DirectoryNotFoundException d)
            {
                Console.WriteLine(d.Message.ToString());
            }
        }

        static void CreateFile()
        {
            FileInfo file = new FileInfo("D:\\example\\test.txt");
            using (StreamWriter sw = file.CreateText())
            {
                sw.WriteLine("Hello File Handling");
            }
            //Display File Info 
            Console.WriteLine("\n\n******Display File Info******");
            Console.WriteLine("File Create on : " + file.CreationTime);
            Console.WriteLine("Directory Name : " + file.DirectoryName);
            Console.WriteLine("Full Name of File : " + file.FullName);
            Console.WriteLine("File is Last Accessed on : " + file.LastAccessTime);
        }
    }
}

Output
Directory Created Successfully. Information of Directory:
Directory Name : example
Path : D:\example
Directory is created on : 01-01-1601 AM 05:30:00
Directory is Last Accessed on 01-01-1601 AM 05:30:00

******Display File Info******
File Create on : 17-08-2016 AM 07:42:30
Directory Name : D:\example
Full Name of File : D:\example\test.txt
File is Last Accessed on : 17-08-2016 AM 07:42:30
_

Summary

In this chapter we have tried to teach you File Handling using programming examples and codes. I am sure that your understanding of file handling would be increased. Next chapter have some programming exercise for you. You must resolve the question before proceeding next.

 

Share your thought