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) //遍历每一行 { } }