ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-05-08 10:03:51  阅读:397  来源: 互联网

标签:Console 读取 filePath C# 文本文件 reader test NET string


一次读取一个字符

//文件路径
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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有