一、網絡流
1. 最常用的方法 Read() Write() Flush()

1 NetworkStream netStream = new NetworkStream(mesock); 2 byte[] nyByte = new Byte[1024]; 3 // Read() : 4 netStream.Read(myByte, 0, myByte.Length); 5 // Write(): 6 netStream.Write(myByte, 0, myByte.Length); 7 netStream.Flush();
二、文本流
1. 文本編碼格式:
ASCII(幾乎支持所有協議) UTF8(支持SMTP協議、POP3協議, 支持漢字傳輸) BigEndianUnicode碼(是雙字節碼,所以一般協議不用這個, 支持漢字傳輸)
<1> 向文件寫文本流

1 StreamWrite sw = null; 2 sw = new StreamWrite("f:\\1.txt", false, System.Text.Encoding.UTF8); // 如文件不存在則創建,存在則打開,並且用新數據覆蓋舊數據 3 sw.Write("寫入的信息"); 4 sw.Close();
<2>打開文件時指定文件權限和編碼格式

1 sw = new StreamWrite("f:\\1.txt", true, System.Text.Encoding.UTF8); // 如文件不存在則創建,存在則打開,並且新數據在舊數據后面
<3> 向網絡寫入文本

1 string data = "abcdefghijklmnopqrstuvwxyz"; 2 byte[] datas = System.Text.Encoding.UTF8.GETBytes(data); 3 NetworkStream netStream = new NetworkStream(mysock); 4 netStream.Write(myByte, 0, myByte.Length);
<4> 從文件讀取文本

1 StreamReader sr = null; 2 sr = new StreamReader("f:\\1.txt", false, System.Text.Encoding.UTF8); 3 string data = sr.ReadToEnd(); 4 sr.Close();
<5> 從網絡讀取文本

1 string data = "abcdefghijklmnopqrstuvwxyz"; 2 byte[] datas = System.Text.Encoding.UTF8.GETBytes(data); 3 NetworkStream netStream = new NetworkStream(mysock); 4 netStream.Read(myByte, 0, myByte.Length);
三、 文件流(主要用於讀寫非文本文件)
<1> 將網絡流數據寫入文件

1 FileStream filestream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); 2 int readNumber = 0; 3 bytep[] byte = new byte[8]; 4 while ( (readNumber = stream.Read(byte, 0, 8)) > 0) 5 { 6 filestream.Write(byte, 0, readNumber); 7 filestream.Flush(); 8 } 9 filestream.Close();
<2> 讀文件並寫入網絡流

1 FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); 2 int number = 0; 3 // 定義緩沖區 4 byte[] bb = new bytep8[]; 5 // 循環讀文件 6 NetworkStream stream = new NetworkStream(newClient); 7 while ( (number=filestream.Read(bb, 0, 8)) != 0) 8 { 9 // 向客戶端發送流 10 stream.Write(bb, 0, 8); 11 }