c# - 将信息附加到文本文件

标签 c# asp.net

我有一个网站,我正在将记录添加到数据库中,并且我还将信息写入作为网站一部分的日志文件。
信息被写入文件很好......我唯一的问题是如何将每个输入的信息添加到数据库中。
由于目前信息被放入 lof 文件,但每次新插入数据库时​​,日志文件中的现有记录似乎被覆盖并替换为新插入,因此始终只有一条记录添加到日志文件。
建议也许...
这是我在 btnClick 事件中使用的代码。

protected void btnSubmitRating_Click1(object sender, EventArgs e)
{
    int rating = 0;
    try
    {
        if (radRating.Items[0].Selected)
        {
            rating = 1;
        }
        if (radRating.Items[1].Selected)
        {
            rating = 2;
        }
        else if (radRating.Items[2].Selected)
        {
            rating = 3;
        }
        else if (radRating.Items[3].Selected)
        {
            rating = 4;
        }
        else if (radRating.Items[4].Selected)
        {
            rating = 5;
        }
        FileStream rate = new FileStream(Server.MapPath("~/rateBooks.log"), FileMode.Open, FileAccess.ReadWrite);
        BufferedStream bs = new BufferedStream(rate);
        rate.Close();


        StreamWriter sw = new StreamWriter(Server.MapPath("~/rateBooks.log"));
        sw.WriteLine("userName " + txtUserName.Text + " " + "bookTitle " + txtBookTitle.Text + " " + "ISBN " + txtISBN.Text);
        sw.Close();


        Service s = new Service();
        s.bookRatedAdd(txtBookTitle.Text, rating, txtReview.Text, txtISBN.Text, txtUserName.Text);
        btnSubmitRating.Enabled = false;
        radRating.Enabled = false;            
    }
    catch (Exception em)
    {
        lblError.Text = em.Message; 
        //lblError.Text = "This book has already been reviewed by yourself?";
    }
}

亲切的问候

最佳答案

更改整个代码块:

FileStream rate = new FileStream(Server.MapPath("~/rateBooks.log"), FileMode.Open, FileAccess.ReadWrite);
BufferedStream bs = new BufferedStream(rate);
rate.Close();

StreamWriter sw = new StreamWriter(Server.MapPath("~/rateBooks.log"));
sw.WriteLine("userName " + txtUserName.Text + " " + "bookTitle " + txtBookTitle.Text + " " + "ISBN " + txtISBN.Text);
sw.Close();

到这一行:
File.AppendAllText(Server.MapPath("~/rateBooks.log"), "userName " + txtUserName.Text + " " + "bookTitle " + txtBookTitle.Text + " " + "ISBN " + txtISBN.Text + Environment.NewLine);

请注意,我现在手动添加 NewLine到每一行。

关于c# - 将信息附加到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963726/

相关文章:

php - http POST 和 http GET 之间的澄清

javascript - 如何从模态对话框下载文件并回发给自身?

asp.net - 如何使用文件上传控件选择多个文件?

c# - 将音频录制到内存流中,然后将其保存到文件中

c# - 标签样式未在窗口状态更改时更新

来自不断增长的文件的 C# WCF 视频流?

asp.net - 将文件从浏览器拖放到桌面/应用程序

c# - 什么会导致 WCF 服务返回类型为 "object"的对象

c# - 如何在整个 Windows 操作系统中更改光标(图像)

asp.net - 在 asp.net 中使用 elrte 编辑器