加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:24:54 所属栏目:百科 来源:网络整理
导读:我编写了以下代码来附加现有数据的数据,但我的代码覆盖了这一点 我应该怎么做代码附加数据的更改. protected void Page_Load(object sender,EventArgs e){ fname = Request.Form["Text1"]; lname = Request.Form["Text2"]; ph = Request.Form["Text3"]; Empc
我编写了以下代码来附加现有数据的数据,但我的代码覆盖了这一点

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

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因为它会在发生异常时自动关闭资源.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读