Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

File System

File System programming in C# allows applications to create, read, write, update, copy, move, and delete files and directories stored on a computer.

C# provides the System.IO namespace for working with files, folders, streams, paths, and other file-related operations.

Key Idea: File handling is commonly used when an application needs to store or retrieve information from files such as text files, configuration files, logs, reports, and exported data.

What is File Handling?

File handling means performing operations on files stored in a file system. A C# application can interact with files through classes provided by the System.IO namespace.

Common file operations include:

  • Create a file
  • Write data to a file
  • Read data from a file
  • Append data to a file
  • Copy a file
  • Move a file
  • Delete a file
  • Check whether a file exists

System.IO Namespace

The System.IO namespace contains classes that provide functionality for working with files, directories, streams, and paths.

Class Purpose
File Provides static methods for file operations
Directory Provides static methods for directory operations
FileInfo Provides instance-based file operations and information
DirectoryInfo Provides instance-based directory operations and information
FileStream Provides a stream for reading and writing file data
StreamReader Reads characters from a text stream
StreamWriter Writes characters to a text stream
Path Works with file and directory path information

Creating a File

The File.Create() method creates a new file at the specified path.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "ciit_student_records.txt";

        File.Create(path);
        
        Console.WriteLine("CIIT Institute student records file created successfully 📩👨‍🏫..!");
    }
}

Output

Output
CIIT Institute student records file created successfully 📩👨‍🏫..!
Note: The file is created in the application's current working directory when only a file name is supplied.

Writing Text to a File

The File.WriteAllText() method creates a file if it does not exist and writes text into it. If the file already exists, its existing content is replaced.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "student.txt";

        File.WriteAllText(
            path,
            "Name: Rahul\nCourse: C# Full Stack"
        );

        Console.WriteLine("Data written successfully✅");
    }
}

Output

Output
Data written successfully✅

File Content

student.txt
Name: Rahul
Course: C# Full Stack

Reading Text from a File

The File.ReadAllText() method reads the complete contents of a text file and returns it as a string.

C#
using System;
 using System.IO;

class Program
{
    static void Main()
    {
        string path = "student.txt";

        string content = File.ReadAllText(path);

        Console.WriteLine(content);
    }
}

Output

Output
Name: Rahul
Course: C# Full Stack

Reading All Lines

The File.ReadAllLines() method reads all lines from a text file and returns them as an array of strings.

C#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "student.txt";

        string[] lines = File.ReadAllLines(path);

        foreach (string line in lines)
        {
            Console.WriteLine(line);
        }
    }
}

Output

Output
Name: Rahul
Course: C# Full Stack

Appending Data to a File

The File.AppendAllText() method adds new content to the end of an existing file without removing its previous content.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "student.txt";

        File.AppendAllText(
            path,
            "\nStatus: Training Completed"
        );

        Console.WriteLine("Data appended successfully✅");
    }
}

Output

Output
Data appended successfully✅

File Content

student.txt
Name: Rahul
Course: C# Full Stack
Status: Training Completed

Checking Whether a File Exists

The File.Exists() method checks whether a file exists at the specified path.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "student.txt";

        if (File.Exists(path))
        {
            Console.WriteLine("File exists.");
        }
        else
        {
            Console.WriteLine("File does not exist.");
        }
    }
}

Output

Output
File exists.

Copying a File

The File.Copy() method creates a copy of an existing file at another location.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string source = "student.txt";
        string destination = "student-copy.txt";

        File.Copy(source, destination, true);

        Console.WriteLine("File copied successfully✅");
    }
}

The third argument true allows the destination file to be overwritten if it already exists.

Moving a File

The File.Move() method moves a file from one location to another.

C#
using System;

using System.IO;

class Program
{
    static void Main()
    {
        string source = "student.txt";
        string destination = "Documents/student.txt";

        File.Move(source, destination);

        Console.WriteLine("File moved successfully.");
    }

}

Deleting a File

The File.Delete() method deletes the specified file.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "student-copy.txt";

        if (File.Exists(path))
        {
            File.Delete(path);

            Console.WriteLine("File deleted successfully.");
        }
    }
}
Important: Always check the file path carefully before deleting files. Deletion is a destructive operation.

Working with Directories

The Directory class provides static methods for creating, checking, listing, and deleting directories.

Creating a Directory

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "StudentData";

        Directory.CreateDirectory(path);

        Console.WriteLine("Directory created.");
    }
}

Output

Output
Directory created.

Checking Directory Exists

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "StudentData";

        if (Directory.Exists(path))
        {
            Console.WriteLine("Directory exists.");
        }
        else
        {
            Console.WriteLine("Directory does not exist.");
        }
    }
}

Getting Files from a Directory

The Directory.GetFiles() method returns the file paths contained in a directory.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string path = "StudentData";

        string[] files = Directory.GetFiles(path);

        foreach (string file in files)
        {
            Console.WriteLine(file);
        }
    }
}

Getting Subdirectories

The Directory.GetDirectories() method returns the directories contained inside another directory.

C#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "StudentData";

        string[] directories =
            Directory.GetDirectories(path);

        foreach (string directory in directories)
        {
            Console.WriteLine(directory);
        }
    }
}

Path Class

The Path class provides methods for working with file and directory paths without directly performing file operations.

Common methods include:

  • Path.Combine()
  • Path.GetFileName()
  • Path.GetExtension()
  • Path.GetDirectoryName()
  • Path.GetFullPath()
C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string folder = "StudentData";
        string file = "students.txt";

        string path = Path.Combine(folder, file);

        Console.WriteLine(path);
        Console.WriteLine(Path.GetFileName(path));
        Console.WriteLine(Path.GetExtension(path));
    }
}

Output

Output
StudentData\students.txt
students.txt
.txt

FileInfo Class

FileInfo provides instance-based operations and information about a specific file.

It can be useful when an application performs multiple operations on the same file.

C#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        FileInfo file = new FileInfo("student.txt");

        Console.WriteLine("File Name: " + file.Name);
        Console.WriteLine("Extension: " + file.Extension);
        Console.WriteLine("Full Path: " + file.FullName);
        Console.WriteLine("Size: " + file.Length + " bytes");
    }
}

DirectoryInfo Class

DirectoryInfo provides instance-based operations and information about a directory.

C#
using System;
using System.IO;

class Program
{
    static void Main()
    {
        DirectoryInfo directory =
            new DirectoryInfo("StudentData");

        Console.WriteLine(
            "Directory Name: " + directory.Name
        );

        Console.WriteLine(
            "Full Path: " + directory.FullName
        );
    }
}

What is a Stream?

A stream represents a flow of data between a source and a destination. Streams are commonly used when reading or writing data.

A file stream allows an application to read or write data to a file progressively rather than treating the entire file as a single string.

Simple Understanding: Think of a stream as a channel through which data moves between your application and a file.

FileStream

FileStream provides a stream for reading and writing bytes to a file.

C#
using System;
 
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string path = "message.txt";

        using (FileStream stream =
               new FileStream(
                   path,
                   FileMode.Create,
                   FileAccess.Write))
        {
            string message = "Hello from C#";

            byte[] data =
                Encoding.UTF8.GetBytes(message);

            stream.Write(data, 0, data.Length);
        }

        Console.WriteLine("Data written using FileStream.");
    }
}

Output

Output
Data written using FileStream.

StreamWriter

StreamWriter is used to write characters and text to a stream or file.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamWriter writer =
               new StreamWriter("students.txt"))
        {
            writer.WriteLine("Amit");
            writer.WriteLine("Priya");
            writer.WriteLine("Rahul");
        }

        Console.WriteLine("Student data written.");
    }
}

Output

students.txt
Student data written.

File Content

students.txt
Amit
Priya
Rahul

StreamReader

StreamReader is used to read characters from a text stream.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        using (StreamReader reader =
               new StreamReader("students.txt"))
        {
            string content = reader.ReadToEnd();

            Console.WriteLine(content);
        }
    }
}

Output

Output
Amit
Priya
Rahul

using Statement with Files

File and stream objects often use system resources such as file handles. The using statement ensures that the object is disposed properly after use.

C#
using (StreamWriter writer =
       new StreamWriter("log.txt"))
{
    writer.WriteLine("Application started.");
}
Best Practice: Dispose file and stream resources properly. The using statement is a simple and reliable way to manage these resources.

Exception Handling in File Operations

File operations can fail for different reasons, such as an invalid path, missing file, insufficient permissions, or a file being unavailable.

Use exception handling when file operations are expected to interact with external resources.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            string content =
                File.ReadAllText("missing.txt");

            Console.WriteLine(content);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("File was not found.");
        }
        catch (IOException)
        {
            Console.WriteLine("File operation failed.");
        }
    }
}

Output

Output
File was not found.

Example: Application Log 🌍📩

Applications often store important events in log files. These logs can help developers understand application behavior and troubleshoot problems.

C#
using System;
 
using System.IO;

class Program
{
    static void Main()
    {
        string logFile = "application.log";

        string message =
            DateTime.Now +
            " - Application started.";

        File.AppendAllText(
            logFile,
            message + Environment.NewLine
        );

        Console.WriteLine("Log entry added.");
    }
}

Possible Output

Output
Log entry added.
CIIT Practical Point: File handling is useful in .NET applications for logging, importing text data, generating reports, storing temporary files, processing uploaded files, and managing application resources.

File vs FileInfo

Feature File FileInfo
Type Static class Instance class
Usage Quick file operations Repeated operations on a specific file
Object Required No Yes
Example File.ReadAllText() file.OpenRead()

Common Mistakes

  1. Using an incorrect file path.
  2. Trying to read a file that does not exist.
  3. Forgetting to dispose streams.
  4. Deleting a file without checking the path.
  5. Ignoring file access permissions.
  6. Assuming that a relative path always points to the project folder.
  7. Loading very large files completely into memory when streaming would be more appropriate.

File Handling Best Practices

  • Validate file paths before performing operations.
  • Check whether a file exists when appropriate.
  • Use using for streams and disposable resources.
  • Handle expected file-related exceptions.
  • Avoid unnecessary file operations.
  • Use streaming APIs for large files when appropriate.
  • Never trust user-provided file paths without validation.

Interview Questions

1. What is file handling in C#?

File handling is the process of creating, reading, writing, updating, copying, moving, and deleting files using C# APIs.

2. Which namespace is used for file handling?

The System.IO namespace provides classes for file, directory, path, and stream operations.

3. What is the difference between File and FileInfo?

File provides static methods for common file operations, while FileInfo provides instance-based operations and information for a specific file.

4. What is FileStream?

FileStream provides a stream for reading and writing bytes to a file.

5. What is StreamReader?

StreamReader is used to read characters from a text stream.

6. What is StreamWriter?

StreamWriter is used to write characters and text to a stream or file.

7. What is the purpose of the using statement?

The using statement ensures that disposable resources such as streams are released properly after use.

8. What is the Path class used for?

The Path class provides methods for creating and analyzing file and directory paths.

Practice Programs

  1. Create a text file and write student information into it.
  2. Read the complete contents of a text file.
  3. Read a file line by line.
  4. Append a new student record to an existing file.
  5. Check whether a specified file exists.
  6. Copy a file from one location to another.
  7. Create a directory and list all files inside it.
  8. Display file name, extension, full path, and file size using FileInfo.
  9. Create a simple application log using AppendAllText().
  10. Read a text file using StreamReader and display its content.

Summary

C# provides powerful file system APIs through the System.IO namespace.

You learned how to create, read, write, append, copy, move, delete, and check files using the File class.

You also learned about Directory, FileInfo, DirectoryInfo, Path, FileStream, StreamReader, and StreamWriter .

Proper resource management, exception handling, path validation, and secure file handling are important when working with files in real-world applications.

File system knowledge is especially useful in applications that handle logs, reports, uploaded files, imports, exports, and local data processing.