Introduction
File I/O (Input/Output) is a fundamental concept in programming that allows you to read from and write to files. In C#, the System.IO namespace provides various classes for handling file operations. This module will cover the basics of file I/O, including reading from and writing to text files, handling binary files, and working with file streams.
Key Concepts
- File Handling Classes:
File,FileInfo,StreamReader,StreamWriter,BinaryReader,BinaryWriter. - Reading and Writing Text Files: Using
StreamReaderandStreamWriter. - Reading and Writing Binary Files: Using
BinaryReaderandBinaryWriter. - File Streams: Understanding
FileStreamfor more control over file operations.
File Handling Classes
File and FileInfo
File: Provides static methods for creating, copying, deleting, moving, and opening files.FileInfo: Provides instance methods for the same operations but allows for more detailed file manipulation.
Comparison Table
| Feature | File (Static) |
FileInfo (Instance) |
|---|---|---|
| Creation | Yes | Yes |
| Deletion | Yes | Yes |
| Copying | Yes | Yes |
| Moving | Yes | Yes |
| Opening | Yes | Yes |
| Detailed Info | No | Yes |
Reading and Writing Text Files
Reading Text Files
To read text from a file, you can use the StreamReader class.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
// Ensure the file exists
if (File.Exists(path))
{
using (StreamReader sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
else
{
Console.WriteLine("File not found.");
}
}
}Writing Text Files
To write text to a file, you can use the StreamWriter class.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("Hello, World!");
sw.WriteLine("This is a text file.");
}
Console.WriteLine("Text written to file.");
}
}Reading and Writing Binary Files
Reading Binary Files
To read binary data from a file, you can use the BinaryReader class.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.bin";
if (File.Exists(path))
{
using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
{
int intValue = br.ReadInt32();
double doubleValue = br.ReadDouble();
Console.WriteLine($"Integer: {intValue}, Double: {doubleValue}");
}
}
else
{
Console.WriteLine("File not found.");
}
}
}Writing Binary Files
To write binary data to a file, you can use the BinaryWriter class.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.bin";
using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
{
bw.Write(42);
bw.Write(3.14159);
}
Console.WriteLine("Binary data written to file.");
}
}File Streams
For more control over file operations, you can use the FileStream class.
Example: Using FileStream to Read and Write
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
// Writing to a file using FileStream
using (FileStream fs = new FileStream(path, FileMode.Create))
{
byte[] info = new UTF8Encoding(true).GetBytes("Hello, FileStream!");
fs.Write(info, 0, info.Length);
}
// Reading from a file using FileStream
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}Practical Exercises
Exercise 1: Reading a Text File
- Create a text file named
data.txtwith some sample text. - Write a C# program to read and display the contents of the file.
Solution:
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "data.txt";
if (File.Exists(path))
{
using (StreamReader sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
else
{
Console.WriteLine("File not found.");
}
}
}Exercise 2: Writing to a Binary File
- Write a C# program to write an integer and a double to a binary file named
data.bin. - Write another program to read and display the values from
data.bin.
Solution:
// Writing to a binary file
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "data.bin";
using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
{
bw.Write(123);
bw.Write(45.67);
}
Console.WriteLine("Binary data written to file.");
}
}// Reading from a binary file
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "data.bin";
if (File.Exists(path))
{
using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
{
int intValue = br.ReadInt32();
double doubleValue = br.ReadDouble();
Console.WriteLine($"Integer: {intValue}, Double: {doubleValue}");
}
}
else
{
Console.WriteLine("File not found.");
}
}
}Conclusion
In this module, you learned how to perform basic file I/O operations in C#. You explored the System.IO namespace and its classes, such as File, FileInfo, StreamReader, StreamWriter, BinaryReader, BinaryWriter, and FileStream. You also practiced reading and writing both text and binary files. Understanding these concepts is crucial for handling data storage and retrieval in real-world applications.
C# Programming Course
Module 1: Introduction to C#
- Introduction to C#
- Setting Up the Development Environment
- Hello World Program
- Basic Syntax and Structure
- Variables and Data Types
Module 2: Control Structures
Module 3: Object-Oriented Programming
- Classes and Objects
- Methods
- Constructors and Destructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced C# Concepts
- Interfaces
- Delegates and Events
- Generics
- Collections
- LINQ (Language Integrated Query)
- Asynchronous Programming
Module 5: Working with Data
Module 6: Advanced Topics
- Reflection
- Attributes
- Dynamic Programming
- Memory Management and Garbage Collection
- Multithreading and Parallel Programming
