File Handling

Using C# we can handle files and folders present in the local drive of the system. This function of handling files and folders using C# is known as File Handling. When you open a file for reading or writing, it becomes stream. Stream is a sequence of bytes traveling from a source to a destination over a communication path. All files and folders related classes available in C# are present inside System.IO namespace. We'll learn more about this using code examples.

CODE

EG 1 . Reading, Writing, Deleting files using C# Code.

//Files and Folders related classes available in C# are present inside following namespace
using System.IO;

namespace projectName{
    class Program{
        static void Main() {
            //------ 1. Printing all file names in Console ------
            string folderPath = @"D:\Personal\Works";
            string[] folderFiles = Directory.GetFiles(folderPath);
            foreach (string folderFile in folderFiles) {
                Console.WriteLine(folderFile);
            }

            //------ 2. Printing only Notepad file names in Console ------
            string folderPath = @"D:\Personal\Works";
            string[] folderFiles = Directory.GetFiles(folderPath, "*.txt");
            foreach (string folderFile in folderFiles) {
                Console.WriteLine(folderFile);
            }

            //------ 3. Deleting all Notepad files in a folder ------
            string folderPath = @"D:\Personal\Works";
            string[] folderFiles = Directory.GetFiles(folderPath, "*.txt");
            foreach (string folderFile in folderFiles) {
                File.Delete(folderFile);
            }

            //------ 4. Creating New file in the folder ------
            File.Create(@"D:\Personal\Works\CodersCapsule.txt");

            //------ 5. Writing content inside file using code ------
            string fileLocation = @"D:\Personal\Works\CodersCapsule.txt";
            File.WriteAllText(fileLocation, "hello there");

            //------ 6. Appending content inside file using code ------
            string fileLocation = @"D:\Personal\Works\CodersCapsule.txt";
            File.AppendAllText(fileLocation, "We are studying File Handling");

            //------ 7. Printing 17th multication table in file using code ------
            string fileLocation = @"D:\Personal\Works\CodersCapsule.txt";
            int tableNumber = 17;
            int limit = 30;
            for (int i = 1; i <= limit; i++) {
                File.AppendAllText(fileLocation, tableNumber + " * " + i + " = " + tableNumber * i + "\n");

            //------ 8. Reading File and printing out in console ------
            string fileLocation = @"D:\Personal\Works\CodersCapsule.txt";
            string[] Lines = File.ReadAllLines(fileLocation);
            foreach (string Line in Lines) {
                Console.WriteLine(Line);
            }
        }
    }
}

(Click Here, For more exercises)