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

swa*_*nil 7 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.........");
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ger 14

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("**********************************************************************");
}
Run Code Online (Sandbox Code Playgroud)

提示:使用using因为它会在发生异常时自动关闭资源.


Blo*_*ard 5

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

将其更改为:

if (!File.Exists(filePath))
Run Code Online (Sandbox Code Playgroud)