在C#中将数据附加到现有文件

我编写了以下代码来附加现有数据的数据,但我的代码覆盖了这一点

我应该怎么做代码附加数据的更改。

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的文档说:

打开文件(如果存在)并搜索到文件末尾,或创建新文件。 此操作需要FileIOPermissionAccess.Append权限。 FileMode.Append只能与FileAccess.Write一起使用。 尝试在文件结束之前寻找位置会抛出IOExceptionexception,并且任何读取尝试都会失败并抛出NotSupportedExceptionexception。

因此不再需要if语句,因为如果文件不存在, FileMode.Append自动创建该文件。

因此,完整的解决方案是:

 using (FileStream aFile = new FileStream(filePath, FileMode.Append, FileAccess.Write)) using (StreamWriter sw = new StreamWriter(aFile)) { sw.WriteLine(Empcode); sw.WriteLine(fname); sw.WriteLine(lname); sw.WriteLine(ph); sw.WriteLine("**********************************************************************"); } 

提示:使用use因为它会自动关闭资源,也就是发生exception时。

您正在创建文件(如果存在),如果不存在则附加。 这与你想要的相反。

将其更改为:

 if (!File.Exists(filePath)) 

你必须把

  if (!File.Exists(filePath)) 

代替

  if (File.Exists(filePath)) 

File.Exists(filePath)更改为!File.Exists(filePath)甚至更好,始终使用追加模式。 如果文件不存在,它将创建该文件

在我看来,if和else语句必须以相反的方式,不是吗?

现在,您创建文件(如果存在),并在文件不存在时添加。 (如果该文件尚不存在,则附加也会创建该文件。)