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.
Section overview
5 resourcesExplores 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
Disposemethod or ausingstatement 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.
StreamWriteris the class used to write characters to a stream.File.CreateTextcreates or opens a file for writing UTF-8 encoded text.sw.WriteLineis 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.
StreamReaderis the class used to read characters from a byte stream.File.OpenTextopens an existing UTF-8 encoded text file for reading.sr.ReadLinereads 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article