C#.NET读取文本文件的几种办法

一次读取一个字符#

//文件路径
string filePath = @"C:\Users\Administrator\Downloads\test\test.txt";

//文本读取器
using(TextReader reader = new StreamReader(filePath,System.Text.Encoding.UTF8))
{
    //一次读一个字符
    int textChar = reader.Read();

    //遍历读取
    while(textChar != -1)
    {
        //输出读取的内容
        Console.Write((char)textChar);
        //停一下
        System.Threading.Thread.Sleep(100);
        //继续读
        textChar = reader.Read();
    }
}

//wait
Console.ReadKey();

一行一行的读#

//文件路径
string filePath = @"C:\Users\Administrator\Downloads\test\test.txt";

//文本读取器
using(TextReader reader = new StreamReader(filePath,System.Text.Encoding.UTF8))
{
    //一次读一行
    string? textLine = reader.ReadLine();

    //遍历读取
    while(textLine != null)
    {
        //输出读取的内容
        Console.WriteLine(textLine);
        //停一下
        System.Threading.Thread.Sleep(1000);
        //继续读
        textLine = reader.ReadLine();
    }
}

//wait
Console.ReadKey();

一次性读取文本文件的所有内容#

//文件路径
string filePath = @"C:\Users\Administrator\Downloads\test\test.txt";

//文本读取器
using(TextReader reader = new StreamReader(filePath,System.Text.Encoding.UTF8))
{
    //一次性读完
    string textContent = reader.ReadToEnd();

    //输出读取的内容
    Console.WriteLine(textContent);
}

//wait
Console.ReadKey();

再简化一点读取所有内容(读取所有行)#

//文件路径
string filePath = @"C:\Users\Administrator\Downloads\test\test.txt";

//直接使用静态方法读取所有行
string[] allLines = File.ReadAllLines(filePath, System.Text.Encoding.UTF8);

//遍历输出
foreach (string line in allLines)
{
    Console.WriteLine(line);
}

//wait
Console.ReadKey();

再简化一点读取所有内容(读取所有内容)#

//文件路径
string filePath = @"C:\Users\Administrator\Downloads\test\test.txt";

//直接使用静态方法读取所有内容
string allContent = File.ReadAllText(filePath,System.Text.Encoding.UTF8);

Console.WriteLine(allContent);

//wait
Console.ReadKey();

作者:重庆熊猫

出处:https://www.cnblogs.com/cqpanda/p/16241154.html

版权:本作品采用「不论是否商业使用都不允许转载,否则按3元1字进行收取费用」许可协议进行许可。

posted @   重庆熊猫  阅读(1042)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示