C#读写txt文件的两种方法介绍
生活随笔
收集整理的這篇文章主要介紹了
C#读写txt文件的两种方法介绍
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.添加命名空間
System.IO;
System.Text;
2.文件的讀取
(1).使用FileStream類進行文件的讀取,并將它轉換成char數組,然后輸出。
byte[] byData = new byte[100];char[] charData = new char[1000];public void Read(){try{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());}}(2).使用StreamReader讀取文件,然后一行一行的輸出。
public void Read(string path){StreamReader sr = new StreamReader(path,Encoding.Default);String line;while ((line = sr.ReadLine()) != null) {Console.WriteLine(line.ToString());}}3.文件的寫入
(1).使用FileStream類創建文件,然后將數據寫入到文件里。
(2).使用FileStream類創建文件,使用StreamWriter類,將數據寫入到文件。
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();}以上就完成了,txt文本文檔的數據讀取與寫入。
?
?
總結
以上是生活随笔為你收集整理的C#读写txt文件的两种方法介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html制作个人简历网页
- 下一篇: linux命令行总结