Codecademy Logo

C# File I/O

C# File Handling

In C#, the File class offers static methods for common file tasks like reading. When work with files is repetitive, use the object-oriented approach of FileInfo, which allows handling these tasks more efficiently. Observe the File and FileInfo usage in the example.

using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
// Using File class for quick operations
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, "Hello, World!");
Console.WriteLine("File created and text written.");
}
// Using FileInfo class for object-oriented operations
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
Console.WriteLine($"File Size: {fileInfo.Length} bytes");
}
}
}

C# File I/O Basics

Handling text files in C# involves understanding text encodings and using the StreamReader and StreamWriter classes. These enable reading from and writing to files efficiently. Use a using statement to ensure file resources are properly closed.

using System;
using System.IO;
class FileExample
{
static void Main()
{
string filePath = "example.txt";
// Writing to a text file
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, world!");
}
// Reading from a text file
using (StreamReader reader = new StreamReader(filePath))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}

C# FileStream Seek

FileStream allows navigation within files using the Seek() method in C#. This operation lets you move to a specific location and read or write data at that point, enhancing file manipulation control. You can also use SetLength() to adjust the file size dynamically.

using System;
using System.IO;
class FileStreamExample
{
static void Main()
{
using (FileStream fileStream = new FileStream("example.txt", FileMode.OpenOrCreate))
{
// Move the file pointer to the 5th byte
fileStream.Seek(5, SeekOrigin.Begin);
// Set the length of the file to 100 bytes
fileStream.SetLength(100);
Console.WriteLine("Pointer moved to 5th byte and file length set to 100 bytes.");
}
}
}

Reading Files in C#

FileStream operations in C# allow reading data from files efficiently. Use Read() for reading a specified number of bytes or ReadByte() for single bytes. This enables handling file data within your program seamlessly.

using System;
using System.IO;
class Program {
static void Main() {
string filePath = "example.txt";
using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) {
int byteData;
while ((byteData = fileStream.ReadByte()) != -1) {
Console.Write((char)byteData);
}
}
}
}

C# FileStream Usage

The FileStream class in C# implements Stream for reading and writing files. It connects your program to the file system, enabling file operations like read, write, and seek.

using System;
using System.IO;
public class FileStreamExample
{
public static void Main()
{
// Specify file path for the FileStream
string filePath = "example.txt";
// Create or open the file
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
{
// Write data
string content = "Hello, FileStream!";
byte[] info = new UTF8Encoding(true).GetBytes(content);
fileStream.Write(info, 0, info.Length);
// Read data
fileStream.Position = 0; // Reset position for reading
byte[] buffer = new byte[info.Length];
fileStream.Read(buffer, 0, buffer.Length);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer));
}
}
}

C# FileStream Writing

In C#, FileStream allows writing bytes to a file. Use the Write() method for multiple bytes and WriteByte() for single bytes. Ensure the file stream is open before writing to avoid exceptions. These operations efficiently transfer data from memory into a file.

using System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
byte[] content = { 72, 101, 108, 108, 111 }; // 'Hello'
using (FileStream fileStream = new FileStream(path, FileMode.Create))
{
fileStream.Write(content, 0, content.Length); // Writes entire content array
fileStream.WriteByte(32); // Writes space character
fileStream.WriteByte(87); // Writes 'W'
}
Console.WriteLine("File written successfully!");
}
}

C# Resource Management

In C#, efficiently manage resources with the IDisposable pattern and the using statement. The IDisposable interface ensures that unmanaged resources like streams or files are properly released. The using statement automates this process, ensuring the resources are closed even if an exception occurs.

using System;
using System.IO;
class ResourceExample
{
static void Main()
{
using (FileStream fileStream = new FileStream("example.txt", FileMode.OpenOrCreate))
{
// Code working with fileStream
} // fileStream.Dispose() is called automatically here
}
}

C# Streams Overview

In C#, a stream is a fundamental component for handling all I/O operations. It manages byte sequences for reading, writing, and seeking operations. Understanding streams is crucial for file processing, network communication, and data manipulation.

using System;
using System.IO;
class StreamExample {
static void Main() {
string fileName = "example.txt";
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Seek(0, SeekOrigin.Begin);
fs.Write(data, 0, data.Length);
Console.WriteLine("File processed successfully.");
}
}
}

FileStream Exception Handling

In C#, handling exceptions with FileStream involves using try-catch blocks to manage I/O exceptions. Common exceptions include FileNotFoundException and IOException. Proper exception handling ensures program stability and data integrity when dealing with file operations like reading or writing.

using System;
using System.IO;
class FileExceptionHandling {
static void Main() {
try {
using (FileStream fileStream = new FileStream("nonexistentfile.txt", FileMode.Open)) {
// Perform file operations
}
} catch (FileNotFoundException e) {
Console.WriteLine("File not found: " + e.Message);
} catch (IOException e) {
Console.WriteLine("An I/O error occurred: " + e.Message);
}
}
}

Learn more on Codecademy