[Implement] Read/Write TXT File
Write TXT File:
以 Write Log 為例
方法1:
if (!System.IO.File.Exists(path))
{
//create file
using (System.IO.FileStream fs = System.IO.File.Create(path))
fs.Close();//release resource
}
System.IO.StreamWriter file = new System.IO.StreamWriter(path, true);//true表示不覆蓋data
file.WriteLine("log...");//write data
file.WriteLine("------------------------------------------------");//分隔線
file.Close();
方法2:
if (!System.IO.File.Exists(path))//若沒有該檔案救create
{
System.IO.FileStream fs = System.IO.File.Create(path);
fs.Close();//release resource
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
{
sw.Write("...");//不換行寫入String
sw.WriteLine("...");//換行寫入String
sw.WriteLine("-------------------------------------------");//分隔線
sw.Flush();
sw.Close();//release resource
}
Read TXT File:
{
string files = string.Empty;
string filePath = System.Environment.CurrentDirectory + "\\test.txt";//webform: Server.MapPath("~")+"\\folder\\test.txt";
if (System.IO.File.Exists(filePath))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
{
string line = string.Empty;
while (!string.IsNullOrEmpty(line = sr.ReadLine()))
files += line + ", ";//抓出每一行以逗點隔開
}
}
return files;
}
P.S System.IO.File 中有許多寫入方法