C# / C# File I/O and Streams

Handling Binary and Text Files

This tutorial will teach you how to handle both binary and text files in C#. You'll learn the differences between the two and how to work with each type.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores file handling and working with streams in C#.

1. Introduction

In this tutorial, we'll guide you through handling both binary and text files in C#. By the end of this tutorial, you will understand the differences between these file types and be able to read from and write to both binary and text files.

Goals:

  • Learn the difference between binary and text files
  • Understand how to read from and write to text and binary files in C#

Prerequisites:

  • Basic understanding of C# and .NET Framework
  • Familiarity with object-oriented programming concepts

2. Step-by-Step Guide

Text Files

Text files are human-readable and contain structured or unstructured text data. They're easy to manipulate and debug, as you can open them in any text editor.

Binary Files

Binary files contain data in a format that's readable by machines but not directly readable by humans. They're more efficient in terms of size and speed compared to text files.

Reading and Writing Text Files

In C#, we use the StreamReader and StreamWriter classes from the System.IO namespace to read from and write to text files.

Reading and Writing Binary Files

To handle binary files, we use BinaryReader and BinaryWriter classes from the System.IO namespace.

3. Code Examples

Example 1: Writing to a Text File

using System.IO;

StreamWriter writer = new StreamWriter("textfile.txt");
writer.WriteLine("Hello, World!");
writer.Close();

This code snippet creates a StreamWriter object, writes a line to a text file, and then closes the file.

Example 2: Reading From a Text File

using System.IO;

StreamReader reader = new StreamReader("textfile.txt");
string line = reader.ReadLine();
Console.WriteLine(line);
reader.Close();

This code snippet creates a StreamReader object, reads a line from a text file, prints the line to the console, and then closes the file.

Example 3: Writing to a Binary File

using System.IO;

BinaryWriter writer = new BinaryWriter(File.Open("binaryfile.bin", FileMode.Create));
writer.Write(12345);
writer.Close();

This code snippet creates a BinaryWriter object, writes an integer value to a binary file, and then closes the file.

Example 4: Reading from a Binary File

using System.IO;

BinaryReader reader = new BinaryReader(File.Open("binaryfile.bin", FileMode.Open));
int number = reader.ReadInt32();
Console.WriteLine(number);
reader.Close();

This code snippet creates a BinaryReader object, reads an integer value from a binary file, prints the number to the console, and then closes the file.

4. Summary

In this tutorial, we've covered the basics of handling text and binary files in C#. We looked at the differences between the two, how to read from and write to these files, and saw practical examples of both.

Next Steps

You can now move on to more advanced topics like handling large files, error handling with file operations, handling file paths, and working with directories.

Additional Resources

5. Practice Exercises

  1. Write a program that reads a text file and prints the number of lines in the file.
  2. Write a program that writes a list of integers to a binary file.
  3. Write a program that reads the list of integers from the binary file and prints them.

Tips

  • Use the File.ReadAllLines() method to read all lines from a text file.
  • Use a foreach loop to write multiple integers to a binary file.
  • Use a while loop to read data from a binary file until the end of the file is reached.

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

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

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