filestream和streamreader
时间: 2024-04-27 15:22:25 浏览: 7
FileStream 和 StreamReader 都是 C# 中用于读取文件的类。其中 FileStream 是用于读取二进制文件的,例如图片、视频等,而 StreamReader 则是用于读取文本文件的。
FileStream 类继承自 Stream 类,可以用于读写文件或其他数据。可用于打开文件流以进行读写、复制、移动和删除文件等操作。FileStream 类中提供了各种读写方法,例如 Read、Write、Seek 等。
StreamReader 类则提供了一些方法来读取文本文件的内容,例如 ReadLine、ReadToEnd 等。它可以读取各种不同编码的文本文件,例如 ASCII、UTF-8 等。
总的来说,FileStream 适用于读取二进制文件,而 StreamReader 适用于读取文本文件。但它们都是 C# 中非常常用的文件读取类。
相关问题
filestream读写文件 c#
在C#中,你可以使用FileStream类来读写文件。下面是一个基本的示例:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
// 文件路径
string filePath = "example.txt";
// 读取文件
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fileStream))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
// 写入文件
using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine("Hello, World!");
}
}
}
}
```
这个示例首先使用FileStream和StreamReader来读取文件的内容,并将其打印到控制台上。接下来,使用FileStream和StreamWriter来向文件中追加写入一行文本。
请记得,使用完FileStream后,需要调用Dispose()方法或使用using语句来释放资源。
StreamReader
StreamReader is a .NET class that provides a way to read characters from a stream in a specific encoding. It is used to read text data from sources such as files, network connections, and memory streams. The StreamReader class can be used to read text data in a variety of encodings, including ASCII, UTF-8, and Unicode. It also provides methods for reading data in specific formats, such as lines or words. The StreamReader class is often used in conjunction with other .NET classes, such as the FileStream and NetworkStream classes, to read data from external sources.