C# - Write To a File and Read It

Write To a File and Read It in C#

In many software applications, handling files for data storage and retrieval is a fundamental skill. C# provides powerful and easy-to-use classes and methods to write data to files and read data from files. This guide covers detailed concepts, techniques, and best practices for working with files in C#, including synchronous and asynchronous operations, file streams, common pitfalls, and code examples.

Introduction to File Handling in C#

File handling involves creating, reading, updating, and deleting files. In C#, the System.IO namespace provides essential classes to perform file operations such as File, FileStream, StreamWriter, StreamReader, and BinaryWriter/BinaryReader. These classes allow working with text and binary files efficiently.

File handling is crucial for persistent data storage, logging, configuration, data exchange, and many other programming tasks.

Key Concepts

  • Text vs Binary Files: Text files store data as human-readable characters, while binary files store data in binary format, suitable for complex data types or compact storage.
  • Synchronous vs Asynchronous IO: Synchronous methods block program execution until the IO operation finishes; asynchronous methods allow the program to continue running while the IO completes.
  • File Paths: Specify the location of the file using absolute or relative paths.
  • File Modes and Access: Determines how a file is opened (create, open, append, etc.) and with what permissions (read, write, read/write).

Writing to a File in C#

Writing to a file means saving data into a file on disk. C# offers multiple ways to write data, ranging from simple one-liners to more complex stream-based solutions.

Using File.WriteAllText()

The easiest way to write text to a file is using the static method File.WriteAllText(). This method creates the file if it doesn't exist or overwrites it if it does.

using System.IO;

string path = "example.txt";
string content = "Hello, this is a sample text.";

File.WriteAllText(path, content);

This method writes the entire string to the file in one operation.

Using File.WriteAllLines()

When you want to write multiple lines at once, File.WriteAllLines() is convenient.

string[] lines = {
    "Line 1",
    "Line 2",
    "Line 3"
};

File.WriteAllLines(path, lines);

This writes each string element as a new line in the file.

Using StreamWriter for Writing to Files

StreamWriter is a flexible class that allows writing text data to files with control over encoding and buffering.

using (StreamWriter writer = new StreamWriter(path))
{
    writer.WriteLine("First line.");
    writer.WriteLine("Second line.");
}

The using statement ensures the file is properly closed and resources are released.

Appending Text to an Existing File

To add content to the end of an existing file without overwriting, use StreamWriter with the append flag set to true.

using (StreamWriter writer = new StreamWriter(path, append: true))
{
    writer.WriteLine("This line will be appended.");
}

Writing Binary Data with BinaryWriter

For writing binary data (e.g., integers, floats, custom objects), BinaryWriter is used.

using (FileStream fs = new FileStream("data.bin", FileMode.Create))
using (BinaryWriter bw = new BinaryWriter(fs))
{
    bw.Write(123);            // Writes an integer
    bw.Write(3.14);           // Writes a double
    bw.Write("Hello World");  // Writes a string
}

Reading from a File in C#

Reading data from a file allows your application to load saved information for processing or display.

Using File.ReadAllText()

This is the simplest way to read the entire contents of a text file as a single string.

string content = File.ReadAllText(path);
Console.WriteLine(content);

Using File.ReadAllLines()

To read a text file line-by-line into a string array:

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

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

Using StreamReader for Reading Files

StreamReader provides a flexible way to read text files line-by-line or in chunks.

using (StreamReader reader = new StreamReader(path))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Reading Binary Data with BinaryReader

To read binary data previously written with BinaryWriter, use BinaryReader.

using (FileStream fs = new FileStream("data.bin", FileMode.Open))
using (BinaryReader br = new BinaryReader(fs))
{
    int number = br.ReadInt32();
    double pi = br.ReadDouble();
    string message = br.ReadString();

    Console.WriteLine($"Number: {number}, Pi: {pi}, Message: {message}");
}

File Modes and File Access

When working with FileStream, it is important to understand the file modes and access types you specify.

FileMode Enumeration

  • CreateNew: Creates a new file; throws if it exists.
  • Create: Creates a new file or overwrites an existing one.
  • Open: Opens an existing file; throws if not found.
  • OpenOrCreate: Opens a file or creates a new one if it doesn’t exist.
  • Append: Opens a file and seeks to the end to append data; creates if missing.
  • Truncate: Opens an existing file and truncates it to zero length.

FileAccess Enumeration

  • Read: File opened for reading only.
  • Write: File opened for writing only.
  • ReadWrite: File opened for both reading and writing.

Exception Handling in File Operations

File operations can fail due to reasons like missing files, permission issues, or hardware problems. It’s important to handle exceptions properly.

Common Exceptions

  • IOException: General I/O error.
  • FileNotFoundException: File does not exist.
  • DirectoryNotFoundException: Invalid path.
  • UnauthorizedAccessException: Access denied.
  • PathTooLongException: Path exceeds system limits.

Example: Handling Exceptions

try
{
    string text = File.ReadAllText("nonexistent.txt");
}
catch (FileNotFoundException ex)
{
    Console.WriteLine("File not found: " + ex.Message);
}
catch (UnauthorizedAccessException ex)
{
    Console.WriteLine("Access denied: " + ex.Message);
}
catch (IOException ex)
{
    Console.WriteLine("IO error: " + ex.Message);
}

Asynchronous File Operations

To avoid blocking the main thread during potentially slow IO operations, C# supports asynchronous file methods using async/await.

Async Writing with WriteAllTextAsync()

await File.WriteAllTextAsync("async.txt", "This is asynchronously written text.");

Async Reading with ReadAllTextAsync()

string content = await File.ReadAllTextAsync("async.txt");
Console.WriteLine(content);

Using Async StreamWriter and StreamReader

using (StreamWriter writer = new StreamWriter("asyncfile.txt"))
{
    await writer.WriteLineAsync("First async line");
}

using (StreamReader reader = new StreamReader("asyncfile.txt"))
{
    string line = await reader.ReadLineAsync();
    Console.WriteLine(line);
}

Working with File Paths

Properly specifying file paths is important to ensure files are located and accessed correctly.

Absolute vs Relative Paths

  • Absolute Path: Complete path from the root, e.g., C:\Data\file.txt.
  • Relative Path: Relative to the application's working directory, e.g., files\data.txt.

Using Path Class

The System.IO.Path class helps construct and manipulate file and directory paths in a platform-independent manner.

string folder = "logs";
string filename = "log1.txt";
string fullPath = Path.Combine(folder, filename);
Console.WriteLine(fullPath);  // Outputs "logs\log1.txt" on Windows

Getting Directory Information

string directory = Path.GetDirectoryName(fullPath);
string extension = Path.GetExtension(fullPath);
string filenameOnly = Path.GetFileName(fullPath);

File and Directory Manipulation

Besides reading and writing, C# allows you to create, delete, move, and copy files and directories.

Creating Directories

string dir = "data";
if (!Directory.Exists(dir))
{
    Directory.CreateDirectory(dir);
}

Deleting Files and Directories

if (File.Exists("oldfile.txt"))
{
    File.Delete("oldfile.txt");
}

if (Directory.Exists("temp"))
{
    Directory.Delete("temp", recursive: true);
}

Copying and Moving Files

File.Copy("source.txt", "dest.txt", overwrite: true);
File.Move("oldname.txt", "newname.txt");

Best Practices for File Handling

  • Always close streams and readers/writers: Use using statements to ensure disposal.
  • Handle exceptions gracefully: Prevent app crashes from IO failures.
  • Use asynchronous methods for UI or server apps: Avoid blocking threads.
  • Validate paths and user input: Prevent security risks and invalid operations.
  • Consider file locking and concurrent access: Use appropriate file modes and locking mechanisms.
  • Prefer Path.Combine for path creation: Ensures platform compatibility.

Complete Example: Writing and Reading a Text File

using System;
using System.IO;

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

        // Write to the file
        string[] linesToWrite = {
            "Line 1: Hello World",
            "Line 2: C# File IO is simple",
            "Line 3: End of file"
        };

        File.WriteAllLines(path, linesToWrite);

        // Read from the file
        string[] linesRead = File.ReadAllLines(path);

        Console.WriteLine("Contents of the file:");
        foreach (string line in linesRead)
        {
            Console.WriteLine(line);
        }
    }
}

C# provides a rich set of APIs for file input and output operations. Whether you need to write simple text files or complex binary data, C#’s System.IO namespace has classes that make the task straightforward and efficient. By mastering these classes and concepts, you can implement robust file handling in your applications.

From the simplest File.WriteAllText to complex asynchronous file streaming, knowing when and how to use these tools is essential for any C# developer.

logo

C#

Beginner 5 Hours

Write To a File and Read It in C#

In many software applications, handling files for data storage and retrieval is a fundamental skill. C# provides powerful and easy-to-use classes and methods to write data to files and read data from files. This guide covers detailed concepts, techniques, and best practices for working with files in C#, including synchronous and asynchronous operations, file streams, common pitfalls, and code examples.

Introduction to File Handling in C#

File handling involves creating, reading, updating, and deleting files. In C#, the System.IO namespace provides essential classes to perform file operations such as File, FileStream, StreamWriter, StreamReader, and BinaryWriter/BinaryReader. These classes allow working with text and binary files efficiently.

File handling is crucial for persistent data storage, logging, configuration, data exchange, and many other programming tasks.

Key Concepts

  • Text vs Binary Files: Text files store data as human-readable characters, while binary files store data in binary format, suitable for complex data types or compact storage.
  • Synchronous vs Asynchronous IO: Synchronous methods block program execution until the IO operation finishes; asynchronous methods allow the program to continue running while the IO completes.
  • File Paths: Specify the location of the file using absolute or relative paths.
  • File Modes and Access: Determines how a file is opened (create, open, append, etc.) and with what permissions (read, write, read/write).

Writing to a File in C#

Writing to a file means saving data into a file on disk. C# offers multiple ways to write data, ranging from simple one-liners to more complex stream-based solutions.

Using File.WriteAllText()

The easiest way to write text to a file is using the static method File.WriteAllText(). This method creates the file if it doesn't exist or overwrites it if it does.

using System.IO;

string path = "example.txt";
string content = "Hello, this is a sample text.";

File.WriteAllText(path, content);

This method writes the entire string to the file in one operation.

Using File.WriteAllLines()

When you want to write multiple lines at once, File.WriteAllLines() is convenient.

string[] lines = {
    "Line 1",
    "Line 2",
    "Line 3"
};

File.WriteAllLines(path, lines);

This writes each string element as a new line in the file.

Using StreamWriter for Writing to Files

StreamWriter is a flexible class that allows writing text data to files with control over encoding and buffering.

using (StreamWriter writer = new StreamWriter(path))
{
    writer.WriteLine("First line.");
    writer.WriteLine("Second line.");
}

The using statement ensures the file is properly closed and resources are released.

Appending Text to an Existing File

To add content to the end of an existing file without overwriting, use StreamWriter with the append flag set to true.

using (StreamWriter writer = new StreamWriter(path, append: true))
{
    writer.WriteLine("This line will be appended.");
}

Writing Binary Data with BinaryWriter

For writing binary data (e.g., integers, floats, custom objects), BinaryWriter is used.

using (FileStream fs = new FileStream("data.bin", FileMode.Create))
using (BinaryWriter bw = new BinaryWriter(fs))
{
    bw.Write(123);            // Writes an integer
    bw.Write(3.14);           // Writes a double
    bw.Write("Hello World");  // Writes a string
}

Reading from a File in C#

Reading data from a file allows your application to load saved information for processing or display.

Using File.ReadAllText()

This is the simplest way to read the entire contents of a text file as a single string.

string content = File.ReadAllText(path);
Console.WriteLine(content);

Using File.ReadAllLines()

To read a text file line-by-line into a string array:

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

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

Using StreamReader for Reading Files

StreamReader provides a flexible way to read text files line-by-line or in chunks.

using (StreamReader reader = new StreamReader(path))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Reading Binary Data with BinaryReader

To read binary data previously written with BinaryWriter, use BinaryReader.

using (FileStream fs = new FileStream("data.bin", FileMode.Open))
using (BinaryReader br = new BinaryReader(fs))
{
    int number = br.ReadInt32();
    double pi = br.ReadDouble();
    string message = br.ReadString();

    Console.WriteLine($"Number: {number}, Pi: {pi}, Message: {message}");
}

File Modes and File Access

When working with FileStream, it is important to understand the file modes and access types you specify.

FileMode Enumeration

  • CreateNew: Creates a new file; throws if it exists.
  • Create: Creates a new file or overwrites an existing one.
  • Open: Opens an existing file; throws if not found.
  • OpenOrCreate: Opens a file or creates a new one if it doesn’t exist.
  • Append: Opens a file and seeks to the end to append data; creates if missing.
  • Truncate: Opens an existing file and truncates it to zero length.

FileAccess Enumeration

  • Read: File opened for reading only.
  • Write: File opened for writing only.
  • ReadWrite: File opened for both reading and writing.

Exception Handling in File Operations

File operations can fail due to reasons like missing files, permission issues, or hardware problems. It’s important to handle exceptions properly.

Common Exceptions

  • IOException: General I/O error.
  • FileNotFoundException: File does not exist.
  • DirectoryNotFoundException: Invalid path.
  • UnauthorizedAccessException: Access denied.
  • PathTooLongException: Path exceeds system limits.

Example: Handling Exceptions

try
{
    string text = File.ReadAllText("nonexistent.txt");
}
catch (FileNotFoundException ex)
{
    Console.WriteLine("File not found: " + ex.Message);
}
catch (UnauthorizedAccessException ex)
{
    Console.WriteLine("Access denied: " + ex.Message);
}
catch (IOException ex)
{
    Console.WriteLine("IO error: " + ex.Message);
}

Asynchronous File Operations

To avoid blocking the main thread during potentially slow IO operations, C# supports asynchronous file methods using async/await.

Async Writing with WriteAllTextAsync()

await File.WriteAllTextAsync("async.txt", "This is asynchronously written text.");

Async Reading with ReadAllTextAsync()

string content = await File.ReadAllTextAsync("async.txt");
Console.WriteLine(content);

Using Async StreamWriter and StreamReader

using (StreamWriter writer = new StreamWriter("asyncfile.txt"))
{
    await writer.WriteLineAsync("First async line");
}

using (StreamReader reader = new StreamReader("asyncfile.txt"))
{
    string line = await reader.ReadLineAsync();
    Console.WriteLine(line);
}

Working with File Paths

Properly specifying file paths is important to ensure files are located and accessed correctly.

Absolute vs Relative Paths

  • Absolute Path: Complete path from the root, e.g., C:\Data\file.txt.
  • Relative Path: Relative to the application's working directory, e.g., files\data.txt.

Using Path Class

The System.IO.Path class helps construct and manipulate file and directory paths in a platform-independent manner.

string folder = "logs";
string filename = "log1.txt";
string fullPath = Path.Combine(folder, filename);
Console.WriteLine(fullPath);  // Outputs "logs\log1.txt" on Windows

Getting Directory Information

string directory = Path.GetDirectoryName(fullPath);
string extension = Path.GetExtension(fullPath);
string filenameOnly = Path.GetFileName(fullPath);

File and Directory Manipulation

Besides reading and writing, C# allows you to create, delete, move, and copy files and directories.

Creating Directories

string dir = "data";
if (!Directory.Exists(dir))
{
    Directory.CreateDirectory(dir);
}

Deleting Files and Directories

if (File.Exists("oldfile.txt"))
{
    File.Delete("oldfile.txt");
}

if (Directory.Exists("temp"))
{
    Directory.Delete("temp", recursive: true);
}

Copying and Moving Files

File.Copy("source.txt", "dest.txt", overwrite: true);
File.Move("oldname.txt", "newname.txt");

Best Practices for File Handling

  • Always close streams and readers/writers: Use using statements to ensure disposal.
  • Handle exceptions gracefully: Prevent app crashes from IO failures.
  • Use asynchronous methods for UI or server apps: Avoid blocking threads.
  • Validate paths and user input: Prevent security risks and invalid operations.
  • Consider file locking and concurrent access: Use appropriate file modes and locking mechanisms.
  • Prefer Path.Combine for path creation: Ensures platform compatibility.

Complete Example: Writing and Reading a Text File

using System;
using System.IO;

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

        // Write to the file
        string[] linesToWrite = {
            "Line 1: Hello World",
            "Line 2: C# File IO is simple",
            "Line 3: End of file"
        };

        File.WriteAllLines(path, linesToWrite);

        // Read from the file
        string[] linesRead = File.ReadAllLines(path);

        Console.WriteLine("Contents of the file:");
        foreach (string line in linesRead)
        {
            Console.WriteLine(line);
        }
    }
}

C# provides a rich set of APIs for file input and output operations. Whether you need to write simple text files or complex binary data, C#’s System.IO namespace has classes that make the task straightforward and efficient. By mastering these classes and concepts, you can implement robust file handling in your applications.

From the simplest File.WriteAllText to complex asynchronous file streaming, knowing when and how to use these tools is essential for any C# developer.

Related Tutorials

Frequently Asked Questions for C#

C# is much easier to learn than C++. C# is a simpler, high-level-of-abstraction language, while C++ is a low-level language with a higher learning curve.

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Python and JavaScript programmers also earn high salaries, ranking #3 and #4 in compensation. 
C# is the highest-paid programming language but has less demand than Python, JavaScript, and Java.

No. Microsoft has invested substantially in ensuring that C# is the dominant language today, spending two billion dollars on marketing and attempting to convince developers to embrace this new platform, which is also based on the.NET foundation.

C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.


You can’t be able to become Master of C# in 3 months since it has many concepts to learn and implement. NOTE: no one can become master in particular programming language. Everyday they introducing new concepts we need to get practice on it which practically somewhat tough.

C-Sharp is one of the most widely used languages for creating system backend.It's because of its incredible features, such as Windows server automation. Apart from that, it's fantastic because it runs codes quite quickly. It can also be used to create CLI applications and game creation.

Easy to learn and use: C# is simpler than Java due to its use of fewer keywords and usually shorter lines of code. Hence, it is easier to learn to code in C# compared to Java. Flexible Data Types: C# provides more flexibility in defining data types than Java.

Four steps of code compilation in C# include : 
  • Source code compilation in managed code.
  • Newly created code is clubbed with assembly code.
  • The Common Language Runtime (CLR) is loaded.
  • Assembly execution is done through CLR.

The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.


The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.


Among other languages, C# is gaining huge popularity for developing web-based applications. Its core concepts help build an interactive environment and provide functionalities that the dynamic web platform requires. Most aspiring full-stack developers choose this versatile language.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270 and 20619) in 2003. Microsoft introduced C# along with .NET Framework and Visual Studio, both of which were closed-source. 

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Yes, C# is used by many large organizations, start-ups and beginners alike. It takes some of the useful features of C and adds syntax to save time and effort. Although C# is based on C, you can learn it without any knowledge of C β€” in fact, this course is perfect for those with no coding experience at all!

C# is a very mature language that evolved significantly over the years.
The C# language is one of the top 5 most popular programming languages and .NET is the most loved software development framework in the world.
TIOBE Index predicts C# as 2023 'Language of the Year' close to overtake Java in popularity.

Generally, the C# language is not limited to the Windows operating system. In a sense, however, it is limited to Microsoft software. C# language "belongs" to Microsoft, it is developed by Microsoft and it is Microsoft that provides the runtime environment required for the operation of programs written in C#.

C# (pronounced "C sharp") is called so because the "#" symbol is often referred to as "sharp." The name was chosen by Microsoft when they developed the language. It's a play on words related to musical notation where "C#" represents the musical note C sharp.

Dennis MacAlistair Ritchie (September 9, 1941 – c. October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B language.

C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.


line

Copyrights © 2024 letsupdateskills All rights reserved