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.
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 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.
In C#, we use the StreamReader
and StreamWriter
classes from the System.IO
namespace to read from and write to text files.
To handle binary files, we use BinaryReader
and BinaryWriter
classes from the System.IO
namespace.
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.
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.
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.
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.
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.
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.
File.ReadAllLines()
method to read all lines from a text file.foreach
loop to write multiple integers to a binary file.while
loop to read data from a binary file until the end of the file is reached.Happy Coding!