對這文章發表回應
發表限制: 非會員 可以發表
發表者: 冷日 發表時間: 2014/10/9 8:33:01
C#讀寫txt檔的兩種方法介紹
1.添加命名空間
System.IO;
System.Text;
2.檔的讀取
(1).使用FileStream類進行檔的讀取,並將它轉換成char陣列,然後輸出。
01.byte[] byData = new byte[100];
02. char[] charData = new char[1000];
03. public void Read()
04. {
05. try
06. {
07. FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
08. file. Seek(0, SeekOrigin.Begin);
09. file. Read(byData, 0, 100); //byData傳進來的位元組陣列,用以接受FileStream物件中的資料,第2個參數是位元組陣列中開始寫入資料的位置,它通常是0,表示從陣列的開端檔中向陣列寫資料,最後一個參數規定從檔讀多少字元.
10. Decoder d = Encoding.Default.GetDecoder();
11. d.GetChars(byData, 0, byData.Length, charData, 0);
12. Console.WriteLine(charData);
13. file. Close();
14. }
15. catch (IOException e)
16. {
17. Console.WriteLine(e.ToString());
18. }
19. }
(2).使用StreamReader讀取檔,然後一行一行的輸出。
01.public void Read(string path)
02. {
03. StreamReader sr = new StreamReader(path,Encoding.Default);
04. String line;
05. while ((line = sr. ReadLine()) != null)
06. {
07. Console.WriteLine(line. ToString());
08. }
09. }
3.檔的寫入
(1).使用FileStream類創建檔,然後將資料寫入到檔裡。
01.public void Write()
02. {
03. FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
04. //獲得位元組陣列
05. byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!");
06. //開始寫入
07. fs. Write(data, 0, data. Length);
08. //清空緩衝區、關閉流
09. fs. Flush();
10. fs. Close();
11. }
(2).使用FileStream類創建檔,使用StreamWriter類,將資料寫入到檔。
01.public void Write(string path)
02. {
03. FileStream fs = new FileStream(path, FileMode.Create);
04. StreamWriter sw = new StreamWriter(fs);
05. //開始寫入
06. sw. Write("Hello World!!!!");
07. //清空緩衝區
08. sw. Flush();
09. //關閉流
10. sw. Close();
11. fs. Close();
12. }
以上就完成了,txt文字文件的資料讀取與寫入。
shadow 發表在 痞客邦 PIXNET 留言(0)
引用(0)
原文出處:C#讀寫txt檔的兩種方法介紹 @ 資訊園 :: 痞客邦 PIXNET ::