C# 寫入檔案,讀取檔案
阿新 • • 發佈:2021-11-22
主要使用IO流的:Directory、File、Stream類來實現
一、寫入檔案
//1.建立目錄(資料夾) string directoryPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"log";//使用當前程式的根目錄 //directoryPath = @"c:/log";//或者儲存在指定目錄 if (Directory.Exists(directoryPath) == false)//沒有該目錄,則建立Directory.CreateDirectory(directoryPath); //2.建立檔案 string fileName = "檔名稱.txt"; string newName = Path.Combine(directoryPath, fileName); if (System.IO.File.Exists(newName) == false) { FileStream fs= System.IO.File.Create(newName); fs.Close(); fs.Dispose(); } //3.在檔案中寫入內容 using (StreamWriter sw = new StreamWriter(newName, true)) { sw.Write("時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n"); }
二、讀取檔案
//newName跟上面一樣,是要讀取檔案的路徑 System.IO.File.ReadAllText(newName);//讀取所有內容 string[] strList = System.IO.File.ReadAllLines(newName);//讀取所有內容儲存到數組裡,每行是一個數組元素