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字进行收取费用」许可协议进行许可。
本文来自博客园,作者:重庆熊猫,转载请注明原文链接:https://www.cnblogs.com/cqpanda/p/16241154.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix