我编写了以下代码来附加现有数据的数据,但我的代码覆盖了这一点
我应该怎么做代码附加数据的更改.
protected void Page_Load(object sender,EventArgs e) { fname = Request.Form["Text1"]; lname = Request.Form["Text2"]; ph = Request.Form["Text3"]; Empcode = Request.Form["Text4"]; string filePath = @"E:Employee.txt"; if (File.Exists(filePath)) { //StreamWriter SW; //SW = File.CreateText(filePath); //SW.Write(text); //SW.Close(); FileStream aFile = new FileStream(filePath,FileMode.Create,FileAccess.Write); StreamWriter sw = new StreamWriter(aFile); sw.WriteLine(Empcode); sw.WriteLine(fname); sw.WriteLine(lname); sw.WriteLine(ph); sw.WriteLine("**********************************************************************"); sw.Close(); aFile.Close(); } else { //sw.Write(text); //sw.Flush(); //sw.Close(); //StreamWriter SW; //SW = File.AppendText(filePath); //SW.WriteLine(text); //SW.Close(); FileStream aFile = new FileStream(filePath,FileMode.Append,FileAccess.Write); StreamWriter sw = new StreamWriter(aFile); sw.WriteLine(Empcode); sw.WriteLine(fname); sw.WriteLine(lname); sw.WriteLine(ph); sw.WriteLine("**********************************************************************"); sw.Close(); aFile.Close(); //System.IO.File.WriteAllText(filePath,text); } Response.Write("Employee Add Successfully........."); }
解决方法
FileMode.Append的
doc说:
Opens the file if it exists and seeks to the end of the file,or creates a new file. This operation requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception,and any attempt to read fails and throws an NotSupportedException exception.
因此不再需要if语句,因为如果文件不存在,FileMode.Append会自动创建该文件.
因此,完整的解决方案是:
using (FileStream aFile = new FileStream(filePath,FileAccess.Write)) using (StreamWriter sw = new StreamWriter(aFile)) { sw.WriteLine(Empcode); sw.WriteLine(fname); sw.WriteLine(lname); sw.WriteLine(ph); sw.WriteLine("**********************************************************************"); }