Csharp/C#教程:Windows系统中使用C#读取文本文件内容的小示例分享

读取文本文件中的内容

此示例读取文本文件的内容以使用System.IO.File选件类的静态方法ReadAllText和ReadAllLines。

classReadFromFile { staticvoidMain() { //Thefilesusedinthisexamplearecreatedinthetopic //Howto:WritetoaTextFile.Youcanchangethepathand //filenametosubstitutetextfilesofyourown. //Example#1 //Readthefileasonestring. stringtext=System.IO.File.ReadAllText(@"C:UsersPublicTestFolderWriteText.txt"); //Displaythefilecontentstotheconsole.Variabletextisastring. System.Console.WriteLine("ContentsofWriteText.txt={0}",text); //Example#2 //Readeachlineofthefileintoastringarray.Eachelement //ofthearrayisonelineofthefile. string[]lines=System.IO.File.ReadAllLines(@"C:UsersPublicTestFolderWriteLines2.txt"); //Displaythefilecontentsbyusingaforeachloop. System.Console.WriteLine("ContentsofWriteLines2.txt="); foreach(stringlineinlines) { //Useatabtoindenteachlineofthefile. Console.WriteLine("t"+line); } //Keeptheconsolewindowopenindebugmode. Console.WriteLine("Pressanykeytoexit."); System.Console.ReadKey(); } }

一次一行地读取文本文件
本示例使用StreamReader类的ReadLine方法将文本文件的内容读取(一次读取一行)到字符串中。所有文本行都保存在字符串line中并显示在屏幕上。

intcounter=0; stringline; //Readthefileanddisplayitlinebyline. System.IO.StreamReaderfile= newSystem.IO.StreamReader(@"c:test.txt"); while((line=file.ReadLine())!=null) { System.Console.WriteLine(line); counter++; } file.Close(); System.Console.WriteLine("Therewere{0}lines.",counter); //Suspendthescreen. System.Console.ReadLine(); 您可能感兴趣的文章:使用C#实现读取系统配置文件的代码实例讲解C#读取Excel的三种方式以及比较分析VS中C#读取app.config数据库配置字符串的三种方法C#实现读取DataSet数据并显示在ListView控件中的方法C#readnodefile()不能读取带有文件名为汉字的osg文件解决方法C#实现读取被进程占用的文件实现方法C#实现读取注册表监控当前操作系统已安装软件变化的方法C#保存与读取DataTable信息到XML格式的方法C#实现xml文件的读取与写入简单实例C#简单读取、改变文件的创建、修改及访问时间的方法

标签: Windows ws ow 系统 示例 do dow

OpenCV图像分割中的分水岭算法原理与应用详解

使用C#编写简单的图形化的可发送附件的邮件客户端程序

上述就是C#学习教程:Windows系统中使用C#读取文本文件内容的小示例分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907006.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐