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

前端之家收集整理的这篇文章主要介绍了在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的 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("**********************************************************************");
}

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

猜你在找的C#相关文章