c#讀寫文件(保存日志,清空文件內容,讀取文件記錄)


c#中讀取文件,可以用來保存日志,寫最近退出時的控件參數,讀文件可以在打開窗口時加載上次退出時的參數信息。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace test
 9 {
10     class SaveParamter
11     {
12         public void writeParam(string strLog)//向parameter.txt中追加字符串
13         {
14             string path = "./parameter.txt";
15             FileStream fs;
16             StreamWriter sw;
17             if (File.Exists(path))
18             {
19                 fs = new FileStream(path, FileMode.Append, FileAccess.Write);
20             }
21             else
22             {
23                 fs = new FileStream(path, FileMode.Create, FileAccess.Write);
24             }
25             sw = new StreamWriter(fs);
26             sw.WriteLine(strLog);
27             sw.Close();
28             fs.Close();
29         }
30         public void clearParam()//清空文件內容
31         {
33             string path = "./parameter.txt";
34             FileStream fs;
35             if (File.Exists(path))
36             {
37                 fs = new FileStream(path, FileMode.Truncate, FileAccess.Write);//Truncate模式打開文件可以清空。
38             }
39             else
40             {
41                 fs = new FileStream(path, FileMode.Create, FileAccess.Write);
42             }
43             fs.Close();
44         }
45     }
46 }

//讀文件。

void fun_Readparamter(Object sender,EventArgs e
{
string[] parArr = File.ReadAllLines("./paramter.txt");//讀文件,將所有行保存在string數組中。 foreach(string par in parArr) //遍歷每一行 { } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM