1.文件流寫入的一般步驟
1.定義一個寫文件流
2.定義一個要寫入的字符串
3.完成字符串轉byte數組
4.把字節數組寫入指定路徑的文件
5.關閉文件流
2.文件流讀入的一般步驟
1.定義一個讀文件流
2.開辟一塊足夠大的字節數組內存空間
3.把指定文件的內容讀入字節數組
4.完成字節數組轉字符串操作
5.關閉文件流
具體代碼如下:
1 using System;
2 using System.IO;
3 using System.Text;
4 namespace LearnFileStream
5 {
6 class Program
7 {
8 string path = @"E:\AdvanceCSharpProject\LearnCSharp\LearnFileStream.txt";
9
10 private void TestWrite()
11 {
12 //定義寫文件流
13 FileStream fsw = new FileStream(path, FileMode.OpenOrCreate);
14 //寫入的內容
15 string inputStr = "Learn Advanced C Sharp";
16 //字符串轉byte[]
17 byte[] writeBytes = Encoding.UTF8.GetBytes(inputStr);
18 //寫入
19 fsw.Write(writeBytes, 0, writeBytes.Length);
20 //關閉文件流
21 fsw.Close();
22 }
23
24 private void TestRead()
25 {
26 //定義讀文件流
27 FileStream fsr = new FileStream(path, FileMode.Open);
28 //開辟內存區域 1024 * 1024 bytes
29 byte[] readBytes = new byte[1024 * 1024];
30 //開始讀數據
31 int count = fsr.Read(readBytes, 0, readBytes.Length);
32 //byte[]轉字符串
33 string readStr = Encoding.UTF8.GetString(readBytes, 0, count);
34 //關閉文件流
35 fsr.Close();
36 //顯示文件內容
37 Console.WriteLine(readStr);
38 }
39 static void Main(string[] args)
40 {
41 new Program().TestWrite();
42 new Program().TestRead();
43 }
44 }
45 }

