Windows10用户联盟QQ群: 227270512 StreamReader和StreamWriter类用于读取和写入数据到文本文件。这些类从抽象基类流,支持读取和写入字节到一个文件流继承。 StreamReader类StreamReader类也继承自抽象基类的TextReader表示读者读取一系列字符。下表描述了一些StreamReader类的常用方法:
例子:下面的例子演示了名为读取Jamaica.txt的文本文件。文件内容如下: Down the way where the nights are gay And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop 代码如下: using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("c:/jamaica.txt")) { string line; // Read and display lines from the file until // the end of the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } Console.ReadKey(); } } } 猜猜当你编译和运行程序是什么显示! StreamWriter类StreamWriter类继承自抽象类TextWriter代表writer,可以写入一系列字符。 下表显示了一些此类的最常用的方法:
对于方法的完整列表,请访问微软的C#文档。 下面的例子演示了使用StreamWriter类将文本写入数据到一个文件中: 例子:using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { string[] names = new string[] {"Zara Ali", "Nuha Ali"}; using (StreamWriter sw = new StreamWriter("names.txt")) { foreach (string s in names) { sw.WriteLine(s); } } // Read and show each line from the file. string line = ""; using (StreamReader sr = new StreamReader("names.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } Console.ReadKey(); } } } Zara Ali Nuha Ali 标签:C# 读取 写入 文本文件
本站文章除注明转载外,均为本站原创或编译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程 转载请注明:文章转载自:易百教程 [http:/www.] 本文标题:C#读取和写入文本文件 本文地址:http://www./csharp/csharp_text_files.html |
|