1. 文件流的基本概念
文件流是C#中处理文件读写的抽象,它提供了对文件内容进行顺序访问的能力。在文件流中,数据按照字节或块的方式传输,而不受文件中数据的格式影响。文件流通常与System.IO命名空间中的类一起使用,包括FileStream、StreamReader和StreamWriter等。
2、使用FileStream类创建一个文件并写入数据:
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\Temp\MyTest.txt";
// 使用FileMode.Create创建新文件,或者覆盖已有的文件
using (FileStream fs = new FileStream(path, FileMode.Create))
{
byte[] data = System.Text.Encoding.UTF8.GetBytes("This is some text");
// 写入数据到文件
fs.Write(data, 0, data.Length);
}
}
}
3、读取文件流中的数据:
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\Temp\MyTest.txt";
// 使用FileMode.Open打开已有的文件
using (FileStream fs = new FileStream(path, FileMode.Open))
{
byte[] data = new byte[1024];
int byteRead = fs.Read(data, 0, data.Length);
// 转换为字符串并显示
Console.WriteLine(System.Text.Encoding.UTF8.GetString(data, 0, byteRead));
}
}
}
4、使用StreamReader和StreamWriter来读写文本文件:
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"C:\Temp\MyTest.bin";
// 使用BinaryWriter写入二进制数据
using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
{
bw.Write("Hello World!");
}
// 使用BinaryReader读取二进制数据
using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
{
string result = br.ReadString();
Console.WriteLine(result);
}
}
}
以上就是一些使用C#文件流的基本方法。在实际应用中,你可能需要根据具体需求来选择合适的类和方法来处理文件流。