C# File I/O and Stream Usage
C# has very strong support for file reading and writing operations. In this article, we will discuss File I/O (Input/Output) operations with C# and the use of streams. File operations are frequently used not only for data sharing between programs but also for persistent data storage. Therefore, File I/O skills are very important during the software development process.
C# File I/O Basics
C# uses the System.IO namespace for file operations. This namespace contains the necessary classes for file and stream operations. Whether it is text files or binary files, these operations can be easily performed with file reader and writer classes.
Writing to a File
The most commonly used class for writing to a file is StreamWriter. Below is an example of writing data to a text file:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "ornek.txt";
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Hello, C# File I/O!");
writer.WriteLine("This file was written with C#.");
}
}
}
Reading a File
To read a file that has been written, the StreamReader class is used. In the example below, we will read the file we previously wrote:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "ornek.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
Stream Usage
Routing data via streams in C# is important for fast access to data. Streams provide a way to perform read or write operations on data. The use of streams is a key feature that increases the speed of file or database operations.
Usage of Memory Stream
In some cases, we use the MemoryStream class to hold data in memory. In the example below, we will create a data stream in memory:
using System;
using System.IO;
class Program
{
static void Main()
{
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] data = { 1, 2, 3, 4, 5 };
memoryStream.Write(data, 0, data.Length);
memoryStream.Position = 0;
byte[] readData = new byte[5];
memoryStream.Read(readData, 0, readData.Length);
Console.WriteLine(string.Join(", ", readData));
}
}
}
With C# File I/O and stream usage, it offers highly effective solutions in file reading, writing and data stream management. If you master these basic concepts, you can easily progress with more comprehensive file operations. You can further develop your knowledge on the subject with more detailed content and examples about C# File I/O.

Yorum Gönder