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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace Example1_FileStream
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. try
  15. {
  16. string file = @"D:\csharp\example.txt";
  17. //Creating File
  18. FileStream fs = new FileStream(file, FileMode.Create);
  19. //Adding current date and time in file
  20. byte[] bdata = Encoding.Default.GetBytes(DateTime.Now.ToString());
  21. fs.Write(bdata, 0, bdata.Length);
  22. Console.WriteLine("Data Added");
  23. fs.Close();
  24. //Reading File
  25. string data;
  26. FileStream fsread = new FileStream(file, FileMode.Open, FileAccess.Read);
  27. using (StreamReader sr = new StreamReader(fsread))
  28. {
  29. data = sr.ReadToEnd();
  30. }
  31. Console.WriteLine(data);
  32. }
  33. catch (Exception e)
  34. {
  35. Console.WriteLine(e.Message.ToString());
  36. }
  37. Console.ReadKey();
  38. }
  39. }
  40. }

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

StreamWriter and StreamReader

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace Example1_Stream
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. string file = @"D:\csharp\example.txt";
  15. //Creating and Writting
  16. using (StreamWriter writer = new StreamWriter(file))
  17. {
  18. writer.Write(DateTime.Now.ToString());
  19. Console.WriteLine("Successfully Added Current Date and Time");
  20. }
  21. //Reading File
  22. using (StreamReader reader = new StreamReader(file))
  23. {
  24. Console.Write("Reading Current Time : ");
  25. Console.WriteLine(reader.ReadToEnd());
  26. }
  27. Console.ReadKey();
  28. }
  29. }
  30. }

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

TextWriter and TextReader

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace Example1_Text
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. string file = @"D:\csharp\example.txt";
  15. //Writting File
  16. using (TextWriter writer = File.CreateText(file))
  17. {
  18. writer.WriteLine(DateTime.Now.ToString());
  19. Console.WriteLine("Successfully Added Current Date and Time");
  20. }
  21. //Reading File
  22. using (TextReader reader = File.OpenText(file))
  23. {
  24. Console.Write("Reading Current Time : ");
  25. Console.WriteLine(reader.ReadToEnd());
  26. }
  27. Console.ReadKey();
  28. }
  29. }
  30. }

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace Example2_Binary
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. string file=@"D:\csharp\example.dat";
  15. using (BinaryWriter writer = new BinaryWriter(File.Open(file, FileMode.Create)))
  16. {
  17. writer.Write("Current Date and Time is : " + DateTime.Now.ToString());
  18. writer.Write(true);
  19. }
  20. using (BinaryReader reader = new BinaryReader(File.Open(file, FileMode.Open, FileAccess.Read)))
  21. {
  22. Console.WriteLine(reader.ReadString());
  23. }
  24. Console.ReadKey();
  25. }
  26. }
  27. }

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace Example3_String
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. string text = "I am reading \n File Handling at \n Complete C# Tutorial.com";
  15. //Writing string into StringBuilder
  16. StringBuilder sb = new StringBuilder();
  17. using (StringWriter writer = new StringWriter(sb))
  18. {
  19. //Store Data on StringBuilder
  20. writer.WriteLine(text);
  21. writer.Flush();
  22. writer.Close();
  23. }
  24. //Read Entry
  25. using (StringReader reader = new StringReader(sb.ToString()))
  26. {
  27. Console.WriteLine(reader.ReadToEnd());
  28. }
  29. Console.ReadKey();
  30. }
  31. }
  32. }

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7.  
  8. namespace example_directory
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. CreateDirectory();
  15. CreateFile();
  16. Console.ReadKey();
  17. }
  18.  
  19. static void CreateDirectory()
  20. {
  21. //Creating Directory
  22. DirectoryInfo dir = new DirectoryInfo("D:\\example");
  23. try
  24. {
  25. //Check If Directory Exists
  26. if (dir.Exists)
  27. {
  28. Console.WriteLine("Directory Already Exists");
  29. Console.WriteLine("Directory Name : " + dir.Name);
  30. Console.WriteLine("Path : " + dir.FullName);
  31. Console.WriteLine("Directory is created on : " + dir.CreationTime);
  32. Console.WriteLine("Directory is Last Accessed on " + dir.LastAccessTime);
  33. }
  34. //Create New Directory
  35. else
  36. {
  37. dir.Create();
  38. Console.WriteLine("Directory Created Successfully. Information of Directory:");
  39. Console.WriteLine("Directory Name : " + dir.Name);
  40. Console.WriteLine("Path : " + dir.FullName);
  41. Console.WriteLine("Directory is created on : " + dir.CreationTime);
  42. Console.WriteLine("Directory is Last Accessed on " + dir.LastAccessTime);
  43. }
  44. }
  45. catch (DirectoryNotFoundException d)
  46. {
  47. Console.WriteLine(d.Message.ToString());
  48. }
  49. }
  50.  
  51. static void CreateFile()
  52. {
  53. FileInfo file = new FileInfo("D:\\example\\test.txt");
  54. using (StreamWriter sw = file.CreateText())
  55. {
  56. sw.WriteLine("Hello File Handling");
  57. }
  58. //Display File Info
  59. Console.WriteLine("\n\n******Display File Info******");
  60. Console.WriteLine("File Create on : " + file.CreationTime);
  61. Console.WriteLine("Directory Name : " + file.DirectoryName);
  62. Console.WriteLine("Full Name of File : " + file.FullName);
  63. Console.WriteLine("File is Last Accessed on : " + file.LastAccessTime);
  64. }
  65. }
  66. }

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