This article will explain simple file operations like creating folder, creating file, appending file and deleting file, using C# code.

Here, we will also check if the Folder and File already exist or not. I hope this code will help a bit in your daily programming life as it is most commonly used.

Create console application and replace the code in Program.cs file.

Program.cs file code

  1. using System;
  2. using System.Text;
  3. using System.IO;
  4. namespace FileOperations
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. string folderPath = @"c:\\RKFolder";
  11. string fileName = "OutputFile.txt";
  12. string filePath = System.IO.Path.Combine(folderPath, fileName);
  13. try
  14. {
  15. CreateFolder(folderPath);
  16. CreateFile(filePath, fileName);
  17. // Adding data to the file
  18. string message = string.Empty;
  19. for (byte i = 0; i < 10; i++)
  20. {
  21. message = "Sample Text - " + i;
  22. AppendTextToFile(filePath, message);
  23. }
  24. Console.WriteLine("\nFile successfully updated on path:\t " + filePath);
  25. Console.WriteLine("Press Enter to Exit...");
  26. Console.ReadLine();
  27. }
  28. catch (Exception ex)
  29. {
  30. Console.WriteLine("Ufff, something went wrong...");
  31. Console.WriteLine(ex.Message);
  32. Console.WriteLine("Press Enter to Exit...");
  33. Console.ReadLine();
  34. }
  35. }
  36. static void AppendTextToFile(string filePath, string message)
  37. {
  38. // Open and append the file
  39. using (System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Append))
  40. {
  41. byte[] info = new UTF8Encoding(true).GetBytes(System.Environment.NewLine + message);
  42. fs.Write(info, 0, info.Length);
  43. }
  44. }
  45. private static void CreateFolder(string folderPath)
  46. {
  47. // Create folder if not present
  48. bool folderExists = Directory.Exists(folderPath);
  49. if (!folderExists)
  50. Directory.CreateDirectory(folderPath);
  51. }
  52. private static void CreateFile(string filePath, string fileName)
  53. {
  54. if (!System.IO.File.Exists(filePath))
  55. {
  56. // Create file
  57. System.IO.FileStream fs = System.IO.File.Create(filePath);
  58. fs.Close();
  59. }
  60. else
  61. {
  62. // Delete the file
  63. Console.WriteLine("File \"{0}\" already exists.", fileName);
  64. File.Delete(filePath);
  65. Console.WriteLine("File deleted...");
  66. // Create the file
  67. System.IO.FileStream fs = System.IO.File.Create(filePath);
  68. fs.Close();
  69. Console.WriteLine("File re-created...");
  70. return;
  71. }
  72. }
  73. }
  74. }

Execute the project. Given below is the output.

File Operations In C#
File Operations In C#