c#怎么读取txt文件

   2025-02-05 6860
核心提示:在C#中,可以使用StreamReader类来读取txt文件。以下是一个示例代码:using System;using System.IO;class Program{static void

在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方法来释放资源。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言