推荐答案
在C#中,文件读写操作可以通过System.IO命名空间中的类来实现。以下是使用File类和StreamReader/StreamWriter类进行文件读写的示例代码:
文件读取
// www.javascriptcn.com code example
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\example.txt";
// 使用File.ReadAllText读取整个文件内容
string content = File.ReadAllText(filePath);
Console.WriteLine(content);
// 使用StreamReader逐行读取文件内容
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}文件写入
// www.javascriptcn.com code example
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\example.txt";
// 使用File.WriteAllText写入整个文件内容
string content = "Hello, World!";
File.WriteAllText(filePath, content);
// 使用StreamWriter逐行写入文件内容
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
}
}
}本题详细解读
文件读取
File.ReadAllText:该方法用于读取整个文件的内容并返回一个字符串。适用于文件较小的情况。StreamReader:该类用于逐行读取文件内容。适用于需要逐行处理大文件的情况。
文件写入
File.WriteAllText:该方法用于将字符串内容写入文件。如果文件已存在,则会覆盖原有内容。StreamWriter:该类用于逐行写入文件内容。适用于需要逐行写入或追加内容的情况。
注意事项
- 文件路径:确保文件路径正确,否则会抛出
FileNotFoundException异常。 - 资源管理:使用
StreamReader和StreamWriter时,建议使用using语句以确保文件流在操作完成后被正确关闭。 - 异常处理:在实际应用中,建议添加异常处理逻辑以应对文件不存在、权限不足等问题。
通过以上方法,你可以在C#中轻松实现文件的读写操作。