C# / C# File I/O and Streams

Introduction to File I/O in C#

This tutorial will introduce you to the basics of file input/output (I/O) in C#. You'll learn about the fundamental concepts and how to implement them in your applications.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores file handling and working with streams in C#.

Introduction to File I/O in C

1. Introduction

In this tutorial, we will cover the basics of File Input/Output (I/O) in C#. File I/O is a critical part of most applications, allowing you to read from and write to files on your computer's hard drive.

By the end of this tutorial, you will be able to:

  • Understand the fundamental concepts of File I/O
  • Implement basic File I/O operations in your C# applications

This tutorial assumes that you have a basic understanding of C# programming. If you're new to C#, you might want to check out some beginner tutorials first.

2. Step-by-Step Guide

C# provides the System.IO namespace which contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.

Here are some of the commonly used classes in the System.IO namespace:

  • FileStream: This class helps in reading from, writing to and closing files.
  • StreamReader / StreamWriter: These classes are used for reading from and writing to character-based streams.
  • BinaryReader / BinaryWriter: These classes are used for reading from and writing to binary streams.

Best Practices

  • Always close the file after performing operations. You can use the Dispose method or a using statement to automatically close the file when you're done with it.
  • Handle exceptions when performing file operations. This will prevent your program from crashing if a file operation fails.

3. Code Examples

Example 1: Writing to a File

using System.IO;

string path = @"C:\temp\MyTest.txt";

// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
    sw.WriteLine("Hello");
    sw.WriteLine("And");
    sw.WriteLine("Welcome");
}

In this example, we are creating a text file and writing some lines to it.

  • StreamWriter is the class used to write characters to a stream.
  • File.CreateText creates or opens a file for writing UTF-8 encoded text.
  • sw.WriteLine is the method used to write a string followed by a line terminator to the text string or stream.

Example 2: Reading from a File

using System.IO;

string path = @"C:\temp\MyTest.txt";

// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
    string s;
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}

In this example, we are reading the lines from the previously created text file.

  • StreamReader is the class used to read characters from a byte stream.
  • File.OpenText opens an existing UTF-8 encoded text file for reading.
  • sr.ReadLine reads a line of characters from the current stream and returns the data as a string.

4. Summary

In this tutorial, we have covered the basics of File I/O in C#. We've learned how to create a text file, write to a file, and read from a file.

As next steps, you can explore more complex operations such as appending to a file, reading and writing binary files, and working with directories.

5. Practice Exercises

Exercise 1: Create a program that writes the numbers 1 to 10 in a text file.

Exercise 2: Create a program that reads the file created in Exercise 1 and prints the numbers to the console.

Exercise 3: Modify the program from Exercise 2 to handle exceptions if the file does not exist.

Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help