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.
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.
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
CIIT Institute student records file created successfully 📩👨🏫..!
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.
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
Data written successfully✅
File Content
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.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "student.txt";
string content = File.ReadAllText(path);
Console.WriteLine(content);
}
}
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.
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
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.
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
Data appended successfully✅
File Content
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.
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
File exists.
Copying a File
The File.Copy() method creates a copy of an
existing file at another location.
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.
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.
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.");
}
}
}
Working with Directories
The Directory class provides static methods
for creating, checking, listing, and deleting directories.
Creating a Directory
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "StudentData";
Directory.CreateDirectory(path);
Console.WriteLine("Directory created.");
}
}
Output
Directory created.
Checking Directory Exists
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.
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.
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()
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
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.
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.
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.
FileStream
FileStream provides a stream for reading and
writing bytes to a file.
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
Data written using FileStream.
StreamWriter
StreamWriter is used to write characters and
text to a stream or file.
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
Student data written.
File Content
Amit
Priya
Rahul
StreamReader
StreamReader is used to read characters from
a text stream.
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
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.
using (StreamWriter writer =
new StreamWriter("log.txt"))
{
writer.WriteLine("Application started.");
}
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.
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
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.
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
Log entry added.
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
- Using an incorrect file path.
- Trying to read a file that does not exist.
- Forgetting to dispose streams.
- Deleting a file without checking the path.
- Ignoring file access permissions.
- Assuming that a relative path always points to the project folder.
- 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
usingfor 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
- Create a text file and write student information into it.
- Read the complete contents of a text file.
- Read a file line by line.
- Append a new student record to an existing file.
- Check whether a specified file exists.
- Copy a file from one location to another.
- Create a directory and list all files inside it.
- Display file name, extension, full path, and file size using FileInfo.
- Create a simple application log using AppendAllText().
- 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.