runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

C#.NET 逐行读取TXT文本

using System;  
using System.IO;  
  
class Program  
{  
    static void Main()  
    {  
        string filePath = @"C:\path\to\your\file.txt"; // 替换为你的TXT文件路径  
        try  
        {  
            // 创建一个StreamReader对象来读取文件  
            using (StreamReader sr = new StreamReader(filePath))  
            {  
                string line;  
                // 逐行读取文件,直到读取完毕  
                while ((line = sr.ReadLine()) != null)  
                {  
                    // 在这里处理每一行,例如打印到控制台  
                    Console.WriteLine(line);  
                }  
            }  
        }  
        catch (Exception e)  
        {  
            // 处理可能出现的异常,例如文件不存在或没有读取权限等  
            Console.WriteLine("The file could not be read:");  
            Console.WriteLine(e.Message);  
        }  
    }  
}

11

posted on 2024-03-20 14:18  runliuv  阅读(29)  评论(0编辑  收藏  举报