随笔 - 130  文章 - 0  评论 - 7  阅读 - 32万

C# 读取txt格式文件内容

读取文件内容有三种方式

a.全部读取到字符串变量中

b.一次读取一行

c.全部读取到字符串数组中,每个数组元素存储一行文本

一次性全部读取到字符串变量

string text = System.IO.File.ReadAllText(@"D:\test.txt");

System.Console.WriteLine("Contents of WriteText.txt = {0}", text);
View Code

一次读取一行

复制代码
int counter = 0;  
string line;  
  
System.IO.StreamReader file =   
    new System.IO.StreamReader(@"d:\test.txt");  
while((line = file.ReadLine()) != null)  
{  
    System.Console.WriteLine(line);  
    counter++;  
}  
  
file.Close();  
System.Console.WriteLine("There were {0} lines.", counter);
View Code
复制代码

全部读取到字符串数组中,每个数组元素存储一行文本

复制代码
string[] lines = System.IO.File.ReadAllLines(@"d:\test.txt");
System.Console.WriteLine("txt = ");
foreach (string line in lines)
{
    Console.WriteLine("\t" + line);
}
View Code
复制代码

 

posted on   donchen-c  阅读(7262)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示