寫內容應該使用UTF8格式,不然讀出來可能會是亂碼
string curTimePath = tmpPath + @"\" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (!Directory.Exists(curTimePath))
{
Directory.CreateDirectory(curTimePath);
}
string newTxtPath = curTimePath + "\\PatientName.txt";
StreamWriter sw = new StreamWriter(newTxtPath, false, Encoding.UTF8);//實例化StreamWriter
string NameShow = "test 測試";
sw.WriteLine(NameShow);
sw.Flush();
sw.Close()
下面引用一片文章,一共兩種方式讀寫
原文地址https://www.cnblogs.com/zoujinhua/p/10808814.html
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類創建文件,然後將數據寫入到文件裏。
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(); }
(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(); }
;