从输入流中读取数据(行读取字符串)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace ConsoleApplication2 { class Class2 { public const string path = "C:/Users/dajun/Desktop/C#/xdj/gadata.txt"; static void Main(string[] args) { //string path = "C:/Users/dajun/Desktop/C#/xdj/gadata.txt"; try { //FileStream aFile = new FileStream(path, FileMode.Open);// 方式一 //StreamReader sr = new StreamReader(aFile); StreamReader sr = new StreamReader(path); //方式二 string strLine = sr.ReadLine(); //Read data in line by line while (strLine != null) { Console.WriteLine(strLine); strLine = sr.ReadLine(); } sr.Close(); } catch (IOException ex) { Console.WriteLine("An IOException has been thrown!"); Console.WriteLine(ex.ToString()); Console.ReadLine(); return; } } } }
2.将流的下一个字符(包括空格和换行)作为正整数值返回
int nChar; nChar = sr.Read(); while (nChar != -1) { //Console.Write(nChar); Console.Write(Convert.ToChar(nChar)); //Console.WriteLine("{0}",nChar); nChar = sr.Read(); } sr.Close();