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
- using System;
- using System.Text;
- using System.IO;
-
- namespace FileOperations
- {
- class Program
- {
- static void Main(string[] args)
- {
- string folderPath = @"c:\\RKFolder";
- string fileName = "OutputFile.txt";
- string filePath = System.IO.Path.Combine(folderPath, fileName);
-
- try
- {
- CreateFolder(folderPath);
- CreateFile(filePath, fileName);
-
-
- string message = string.Empty;
- for (byte i = 0; i < 10; i++)
- {
- message = "Sample Text - " + i;
- AppendTextToFile(filePath, message);
- }
- Console.WriteLine("\nFile successfully updated on path:\t " + filePath);
- Console.WriteLine("Press Enter to Exit...");
- Console.ReadLine();
- }
- catch (Exception ex)
- {
- Console.WriteLine("Ufff, something went wrong...");
- Console.WriteLine(ex.Message);
-
- Console.WriteLine("Press Enter to Exit...");
- Console.ReadLine();
- }
- }
- static void AppendTextToFile(string filePath, string message)
- {
-
- using (System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Append))
- {
- byte[] info = new UTF8Encoding(true).GetBytes(System.Environment.NewLine + message);
- fs.Write(info, 0, info.Length);
- }
- }
- private static void CreateFolder(string folderPath)
- {
-
- bool folderExists = Directory.Exists(folderPath);
- if (!folderExists)
- Directory.CreateDirectory(folderPath);
- }
-
- private static void CreateFile(string filePath, string fileName)
- {
- if (!System.IO.File.Exists(filePath))
- {
-
- System.IO.FileStream fs = System.IO.File.Create(filePath);
- fs.Close();
- }
- else
- {
-
- Console.WriteLine("File \"{0}\" already exists.", fileName);
- File.Delete(filePath);
- Console.WriteLine("File deleted...");
-
-
- System.IO.FileStream fs = System.IO.File.Create(filePath);
- fs.Close();
- Console.WriteLine("File re-created...");
- return;
- }
- }
- }
- }
Execute the project. Given below is the output.