標籤:
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;namespace CommonLib{ /// <summary> /// 檔案的讀寫 /// </summary> public class FileHelper { /// <summary> /// 使用FileStream類進行檔案的讀取,並將它轉換成char數組,然後輸出 /// </summary> public void Read() { try { byte[] byData = new byte[100]; char[] charData = new char[1000]; FileStream file = new FileStream("E:\\test.txt", FileMode.Open); file.Seek(0, SeekOrigin.Begin); file.Read(byData, 0, 100); //byData傳進來的位元組數組,用以接受FileStream對象中的資料,第2個參數是位元組數組中開始寫入資料的位置,它通常是0,表示從數組的開端檔案中向數組寫資料,最後一個參數規定從檔案讀多少字元. Decoder d = Encoding.Default.GetDecoder(); d.GetChars(byData, 0, byData.Length, charData, 0); Console.WriteLine(charData); file.Close(); } catch (IOException e) { Console.WriteLine(e.ToString()); } } /// <summary> /// 使用StreamReader讀取檔案,然後一行一行的輸出 /// </summary> /// <param name="path"></param> public void Read(string path) { StreamReader sr = new StreamReader(path, Encoding.Default); String line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line.ToString()); } } /// <summary> /// 使用FileStream類建立檔案,然後將資料寫入到檔案裡 /// </summary> public void Write() { FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create); //獲得位元組數組 byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!"); //開始寫入 fs.Write(data, 0, data.Length); //清空緩衝區、關閉流 fs.Flush(); fs.Close(); } /// <summary> /// 使用FileStream類建立檔案,使用StreamWriter類,將資料寫入到檔案 /// </summary> /// <param name="path"></param> public void Write(string path) { FileStream fs = new FileStream(path, FileMode.Create); StreamWriter sw = new StreamWriter(fs); //開始寫入 sw.Write("Hello World!!!!"); //清空緩衝區 sw.Flush(); //關閉流 sw.Close(); fs.Close(); } }}
C# 讀寫Txt檔案