在 C# WinForms 中,您可以使用 System.IO 命名空间中的类来读取和写入文件。以下是一些常用的方法:

  1. 读取文件:
string filePath = 'C:\path\to\file.txt';
string content = File.ReadAllText(filePath); // 读取整个文件内容到一个字符串中

// 或者使用 StreamReader 逐行读取文件内容
using (StreamReader reader = new StreamReader(filePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // 处理每一行的内容
    }
}
  1. 写入文件:
string filePath = 'C:\path\to\file.txt';
string content = 'Hello, World!';

// 将字符串内容写入文件
File.WriteAllText(filePath, content);

// 使用 StreamWriter 写入文件内容
using (StreamWriter writer = new StreamWriter(filePath))
{
    writer.WriteLine('Line 1');
    writer.WriteLine('Line 2');
    // 写入更多内容
}

请根据您的需求选择适合的方法来读取和写入文件。在使用这些方法时,请确保您具有足够的文件访问权限,并提供正确的文件路径。

C# WinForms 文件读写指南:使用 System.IO 操作文件

原文地址: https://www.cveoy.top/t/topic/CDW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录