摘要:資料流I/O與檔案
引入地方
using system.io
寫檔部分
StreamWriter sw = new StreamWriter(檔案路徑); //一般寫法
StreamWriter sw = File.AppendText(檔案路徑); //把字串寫在既有的檔案尾端
StreamWriter sw = File.AppendAllText(檔案路徑,追加內容); //跟AppendText不同的是若檔案不存在會自動新增
StreamWriter sw = File.CreateText(檔案路徑) //新增檔案
sw.WriteLine("我接著寫"); //寫完後自動換航
sw.Write("字串");
sw.Close();
讀檔部分
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(檔案路徑)
{
do
{
sb.Append(sr.ReadLine()+"\n");
} while (sr.ReadLine() != null);
sr.Close();
Response.Write(sb);
}
檔案部分
判斷資料夾存不存在,不存在則建立
if (!Directory.Exists(sPath))
{
Directory.CreateDirectory(sPath);
}
取得資料夾路徑下所有檔案
StringBuilder sb = new StringBuilder();
string sPath = Server.MapPath("~");
DirectoryInfo my_dir = new DirectoryInfo(sPath);
FileInfo[] file = my_dir.GetFiles();
foreach (FileInfo fi in file)
{
sb.Append("檔案名稱:" + fi.Name + "<br>");
sb.Append("大小:" + fi.Length + "<br>");
sb.Append("<hr>");
}