编程语言
首页 > 编程语言> > C#.NET读取文本文件的几种办法

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();

标签:Console,读取,filePath,C#,文本文件,reader,test,NET,string
来源: https://www.cnblogs.com/cqpanda/p/16241154.html