c#读写INI文件做历史信息菜单日志
读写INI文件的类
技巧1 address = System.Environment.CurrentDirectory;取得当前的目录
2 使用StreamWriter 类 写入
using System; using System.IO; class Test { public static void Main() { //将数据写入TestFile.txt类中间 using (StreamWriter sw = new StreamWriter("TestFile.txt")) { sw.Write("This is the "); sw.WriteLine("header for the file."); sw.WriteLine("-------------------"); sw.Write("The date is: "); sw.WriteLine(DateTime.Now); } } }
使用StreamReader 类 读取
using System; using System.IO; class Test { public static void Main() { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("TestFile.txt")) { String line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } }
使用 在MDIFROM LOAD的时候 读取INI文件
private void Form1_Load(object sender, EventArgs e) { StreamReader sr = new StreamReader(address + "\\Menu.ini"); int i = this.文件ToolStripMenuItem.DropDownItems.Count-2; while (sr.Peek()>=0) { ToolStripMenuItem menuitem = new ToolStripMenuItem(sr.ReadLine()); this.文件ToolStripMenuItem.DropDownItems.Insert(i, menuitem); i++; menuitem.Click += new EventHandler(menuitem_Click); } sr.Close(); }
每次打开的时候写入
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog1.FileName = ""; this.openFileDialog1.ShowDialog(); StreamWriter s = new StreamWriter(address + "\\Menu.ini", true); s.WriteLine(openFileDialog1.FileName); s.Flush(); s.Close(); }
这样就可以在每次开打的时候看到读取的历史文件了
如果在读取的时候加个限制 如果说10个文件以内,那么很简单只要在读取的时候循环加一个限制就OK