c#第九课 linq stream(2)
流用于对IO处理
在System.IO名称空间中有以下类
BinaryReader/Writer
TextReader/Writer
Stream
其中类Stream为抽象类。由此有三个派生类:
MemoryStream:对内存进行读取与写入
BufferedStream:对缓冲器进行读取/写入
FileStream:对文件执行读取与写入
TextReader/Writer为抽象类。由此派生类:
StreamReader/StreamWirter
StringReader/StreamWriter
需要引入命名空间:
using System.IO
文件流的使用
string s=Console.ReadLine(); FileStream fileStream=new FileStream(s,FileMode.OpenOrCreate); BinaryWriter binStream=new BinaryWriter (fileStream); for(int i=1;i<=10;i++) { binStream.Write((int)i); } binStream.Close(); fileStream.Close(); FileStream f=new FileStream(s,FileMode.Open,FileAccess.Read,FileShare.ReadWrite); BinaryReader buf=new BinaryReader(f); for(int i=1;i<10;i++) { Console.WriteLine("输出{0}",buf.ReadByte ()); //在vs2012中这样不能读出东西来 Console.WriteLine("输出{0}",Bur.ReadInt32());才行,因为int是32位的 }
2 递归显示目录
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Text; 5 6 namespace StreamTester 7 { 8 class Tester 9 { 10 static int dirCounter = 1; 11 static int indentLevel = -1; 12 13 public static void Main() 14 { 15 Tester t = new Tester(); 16 17 // 选择根目录 18 string theDirectory = 19 Environment.GetEnvironmentVariable("SystemRoot"); 20 // 如果是在unix linux 等其他系统下,要加下面一句话 21 //string theDirectory = "/tmp"; 22 23 //下面调用方法来浏览该目录,显示数据及子目录 24 25 DirectoryInfo dir = new DirectoryInfo(theDirectory); 26 27 t.ExploreDirectory(dir); 28 29 Console.WriteLine( 30 "\n\n{0} directories found.\n", 31 dirCounter); 32 } 33 34 // 只要找到一个目录就递归的递归的调用自己 35 36 private void ExploreDirectory(DirectoryInfo dir) 37 { 38 indentLevel++; // 目录层次++ 39 40 for (int i = 0; i < indentLevel; i++) 41 Console.Write(" "); 42 43 Console.WriteLine("[{0}] {1} [{2}]\n", 44 indentLevel, dir.Name, dir.LastAccessTime); 45 46 // 得到dir下的所有子目录存入directories[]中 47 DirectoryInfo[] directories = dir.GetDirectories(); 48 foreach (DirectoryInfo newDir in directories) 49 { 50 dirCounter++; 51 ExploreDirectory(newDir); // 递归调用 52 } 53 indentLevel--; //目录层次-- 54 } 55 } 56 }
结果显示为
读网页内容
1 public class Client 2 { 3 static public void Main(string[] Args) 4 { 5 // http request请求 6 HttpWebRequest webRequest = 7 (HttpWebRequest)WebRequest.Create 8 ("http://www.baidu.com/"); 9 10 // httq response 11 HttpWebResponse webResponse = 12 (HttpWebResponse)webRequest.GetResponse(); 13 14 // 对response的返回内容读入 15 StreamReader streamReader = new StreamReader( 16 webResponse.GetResponseStream(), Encoding.ASCII); 17 18 try 19 { 20 string outputString; 21 outputString = streamReader.ReadToEnd(); 22 Console.WriteLine(outputString); 23 } 24 catch 25 { 26 Console.WriteLine("Exception reading from web page"); 27 } 28 streamReader.Close(); 29 Console.ReadKey(); 30 } 31 }
输出结果为