IO文件讀寫操做

若是是操做文本文件類型數組

推薦使用:  StreamReader、StreamWriterapp

示例:StreamWriter 用於寫入,能夠使用 WriteLine(xxx) 函數將內容寫入指定文件當中函數

 1 try
 2 {
 3     //StreamWriter用於將內容寫入文本文件中
 4     //path: 要寫入文件的路徑
 5     //append: true 將數據追加到該文件的末尾; false 覆蓋該文件。
 6     //Encoding.UTF8  寫入的編碼格式
 7     //若是指定的文件不存在,構造函數將建立一個新文件。
 8     using (StreamWriter sw = new StreamWriter(@"D:\aaa.txt", true, Encoding.UTF8))
 9     {
10         sw.WriteLine("我是老大");
11         sw.WriteLine("我是老三");
12         sw.WriteLine("我是老四");
13         sw.WriteLine("我是老五");
14         sw.Close();
15     }
16     Console.WriteLine("寫入成功了。。。");
17 }
18 catch (Exception ex)
19 {
20     Console.WriteLine(ex.Message);
21 }

若是文件不存在,會自動建立。編碼

 StreamReader  用於讀取,ReadLine 表示一行行讀取,還有其餘讀取方法,具體到程序集查看便可spa

 1 //StreamReader用法
 2 try
 3 {
 4     using (StreamReader sr = new StreamReader(@"D:\aaa.txt", Encoding.UTF8))
 5     {
 6         while (true)
 7         {
 8             var str = sr.ReadLine();  //一行行的讀取
 9             if (str == null)          //讀到最後會返回null
10             {
11                 break;
12             }
13             Console.WriteLine(str);
14         }
15         sr.Close();
16     }
17     Console.WriteLine("讀取結束了。。。");
18 }
19 catch (Exception ex)
20 {
21     Console.WriteLine(ex.Message);
22 }

若是是操做 其餘類型的文件(包括文本文件),能夠使用 FileStream,3d

好比咱們操做一張圖片文件code

 1 //FileStream 用法  讀取文件
 2 try
 3 {
 4     //FileMode.OpenOrCreate   表示文件不存在,會建立一個新文件,存在會打開
 5     using (Stream fs = new FileStream(@"D:\123.jpg", FileMode.OpenOrCreate))
 6     {
 7         byte[] bt = new byte[fs.Length];  //聲明存放字節的數組
 8         while (true)
 9         {
10             var num = fs.Read(bt, 0, bt.Length);   //將流以byte形式讀取到byte[]中
11             if (num <= 0)
12             {
13                 break;
14             }
15         }
16         fs.Close();
17 
18 
19         //將 123.jpg 文件中讀到byte[]中,而後寫入到 456.jpg
20         //FileAccess.ReadWrite  表示支持讀和寫操做
21         using (Stream fs2 = new FileStream(@"D:\456.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite))
22         {
23             //設置字節流的追加位置從文件的末尾開始,若是文件不存在,只默認0開始
24             fs2.Position = fs2.Length;
25 
26             //將待寫入內容追加到文件末尾  
27             fs2.Write(bt, 0, bt.Length);
28 
29             //關閉
30             fs2.Close();
31         }
32     }
33 }
34 catch (Exception ex)
35 {
36     Console.WriteLine(ex.Message);
37 }

生成效果以下blog

相關文章
相關標籤/搜索