在 C# 中,实现读写文件有多种方式,下面将分别介绍常见的几种读写文件的方法,包括使用 File 类、FileStream 类、StreamReader 和 StreamWriter 类以及 FileInfo 类等。
File 类是一个静态类,提供了许多便捷的方法来进行文件的读写操作,适合处理简单的文件读写任务。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
string content = "这是要写入文件的内容。";
// 使用 WriteAllText 方法将字符串写入文件
File.WriteAllText(filePath, content);
Console.WriteLine("文件写入成功。");
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
// 使用 ReadAllText 方法读取文件内容
string content = File.ReadAllText(filePath);
Console.WriteLine("文件内容:");
Console.WriteLine(content);
}
}
FileStream 类提供了对文件的底层读写操作,适合处理大型文件或需要更精细控制的文件读写场景。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
string content = "这是使用 FileStream 写入的内容。";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(content);
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
fs.Write(buffer, 0, buffer.Length);
Console.WriteLine("文件写入成功。");
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string content = System.Text.Encoding.UTF8.GetString(buffer);
Console.WriteLine("文件内容:");
Console.WriteLine(content);
}
}
}
StreamReader 和 StreamWriter 类提供了基于字符的读写操作,适合处理文本文件。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
string content = "这是使用 StreamWriter 写入的内容。";
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(content);
Console.WriteLine("文件写入成功。");
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
using (StreamReader sr = new StreamReader(filePath))
{
string content = sr.ReadToEnd();
Console.WriteLine("文件内容:");
Console.WriteLine(content);
}
}
}
FileInfo 类是一个实例类,它提供了与 File 类类似的功能,但它更适合在需要多次操作同一个文件的场景中使用。
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
string content = "这是使用 FileInfo 写入的内容。";
FileInfo fileInfo = new FileInfo(filePath);
using (StreamWriter sw = fileInfo.CreateText())
{
sw.Write(content);
Console.WriteLine("文件写入成功。");
}
}
}
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "test.txt";
FileInfo fileInfo = new FileInfo(filePath);
using (StreamReader sr = fileInfo.OpenText())
{
string content = sr.ReadToEnd();
Console.WriteLine("文件内容:");
Console.WriteLine(content);
}
}
}
- 在使用文件操作时,要确保有足够的权限访问文件,避免出现
UnauthorizedAccessException 异常。
- 使用
using 语句可以确保文件资源在使用完毕后被正确释放,避免资源泄漏。
- 对于不同的文件编码,要使用相应的编码方式进行读写操作,例如 UTF-8、GB2312 等。