8

我已经编写了以下代码来将数据附加到现有数据中,但是我的代码会覆盖它

我应该如何更改代码附加数据。

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.........");
}
4

5 回答 5

22

FileMode.Append的文档说:

如果文件存在,则打开文件并查找文件末尾,或创建一个新文件。此操作需要 FileIOPermissionAccess.Append 权限。FileMode.Append 只能与 FileAccess.Write 结合使用。试图在文件结尾之前寻找一个位置会引发 IOException 异常,任何读取尝试都会失败并引发 NotSupportedException 异常。

因此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("**********************************************************************");
}

提示:使用using,因为它会自动关闭资源,发生异常时也是如此。

于 2012-06-08T09:42:07.270 回答
5

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

将其更改为:

if (!File.Exists(filePath))
于 2012-06-08T09:42:27.067 回答
3

你必须把

  if (!File.Exists(filePath)) 

代替

  if (File.Exists(filePath))
于 2012-06-08T09:41:54.517 回答
1

更改File.Exists(filePath)!File.Exists(filePath) 或者更好的是,始终使用附加模式。如果文件不存在,它将创建文件

于 2012-06-08T09:44:31.820 回答
0

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

现在您创建文件,当它存在时,并在它不存在时追加。(如果该文件尚不存在,Append 也会创建该文件。)

于 2012-06-08T09:46:34.067 回答