How to use streams for file operations in C#
In C#, you can use streams to perform file operations. Below is a simple example demonstrating how to use streams to read file contents and write them to a new file.
using System;
using System.IO;
class Program
{
static void Main()
{
string sourceFilePath = "source.txt";
string destinationFilePath = "destination.txt";
// 读取源文件内容
using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(sourceStream))
{
string content = reader.ReadToEnd();
// 写入新文件
using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(destinationStream))
{
writer.Write(content);
}
}
}
}
Console.WriteLine("文件操作完成!");
}
}
In the example above, the content of the source file is first read using FileStream and StreamReader, and then the read content is written to a new file using FileStream and StreamWriter. Finally, a message indicating the completion of the file operations is displayed on the console.
It is important to remember to close the stream object in a timely manner when using stream operations to release resources. The ‘using’ statement can be used to automatically close the stream object.