C#语言如何读取txt文件

一、在C#语言中,可以使用 StreamReader 类来读取 txt 文件。

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "your_file_path.txt";  // 将这里替换为您实际的文件路径

        try
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine())!= null)
                {
                    Console.WriteLine(line);  // 可以根据需要对读取的每行内容进行处理
                }
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("文件未找到!");
        }
        catch (IOException e)
        {
            Console.WriteLine("发生 I/O 错误: " + e.Message);
        }
    }
}

以上代码中:

  • StreamReader :类用于从文本文件中以一种方便的方式读取字符数据。
  • reader:这是创建的 StreamReader 对象的名称,通过这个名称可以调用 StreamReader 类提供的方法来操作文件的读取。
  • new StreamReader(filePath):这里使用 new 关键字创建了一个 StreamReader 对象;filePath :通常是一个表示文件路径的字符串。

使用 reader 对象,可以通过以下常见的方法来读取文件的内容:

  • ReadLine():读取文件的一行内容,并返回一个字符串。
  • ReadToEnd():读取文件的全部内容,并返回一个字符串。

二、另外,还可以一次性读取整个文件的内容,如下所示:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "your_file_path.txt";  // 替换为实际路径

        try
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string content = reader.ReadToEnd();
                Console.WriteLine(content);  // 对读取的全部内容进行处理
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("文件未找到!");
        }
        catch (IOException e)
        {
            Console.WriteLine("发生 I/O 错误: " + e.Message);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值