c#

c#怎么读取txt文件

小亿
105
2024-01-12 01:40:13
栏目: 编程语言

在C#中,可以使用StreamReader类来读取txt文件。以下是一个示例代码:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            // 指定txt文件的路径
            string path = @"C:\example.txt";

            // 创建一个StreamReader对象来读取文件
            using (StreamReader sr = new StreamReader(path))
            {
                string line;

                // 一次读取一行,直到文件的末尾
                while ((line = sr.ReadLine()) != null)
                {
                    // 打印每一行的内容
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("读取文件出错:" + e.Message);
        }
    }
}

在上面的示例中,我们使用StreamReader类打开一个txt文件,然后使用ReadLine方法逐行读取文件内容,并将每一行打印到控制台。请注意,使用完StreamReader后,需要使用using语句或手动调用Dispose方法来释放资源。

0
看了该问题的人还看了