c# - 如何使用 C# 在 ASP.NET 中覆盖(不追加)文本文件

标签 c# asp.net

我在我的网站中包含了一个包含多行的文本文件。 我在页面中放置了一个文本框 (Multimode=true) 和一个按钮。 在 Page_Load 上,文本文件中的内容应显示在文本框中。 然后用户可以编辑文本框。单击按钮时,文本框的当前内容应在该文本文件中被覆盖(不应附加)。

我成功地在文本框中显示了文本文件数据。但是在覆盖时,它会附加到文本文件中而不是覆盖。

这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (File.Exists(Server.MapPath("newtxt.txt")))
    {
        StreamReader re = new StreamReader(Server.MapPath("newtxt.txt"));
        while ((input = re.ReadLine()) != null)
        {
           TextBox1.Text += "\r\n";
           TextBox1.Text += input;              
        }
        re.Close();
    }

    else
    {
        Response.Write("<script>alert('File does not exists')</script>");
    }       
}

protected void Button1_Click(object sender, EventArgs e)
{
    StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt"));
    wr.Write("");
    wr.WriteLine(TextBox1.Text);
    wr.Close();
    StreamReader re = new StreamReader(Server.MapPath("newtxt.txt"));
    string input = null;
    while ((input = re.ReadLine()) != null)
    {
        TextBox1.Text += "\r\n";
        TextBox1.Text += input;
    }
    re.Close();
} 

如何覆盖文本文件,然后在单击同一按钮时将其显示在我的文本框中?

最佳答案

StreamWriter 构造函数有多个重载,其中一个用于指定是追加还是覆盖。

StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt"), false);

From MSDN , 第二个参数:

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

关于c# - 如何使用 C# 在 ASP.NET 中覆盖(不追加)文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5603274/

相关文章:

c# - Discord OAuth 代码使用

c# - 检查远程网络服务器上是否存在 .txt 文件

c# - 自定义验证器并指定消息类型

c# - 如何在asp.net中访问同一类的其他方法中的页面加载方法

javascript - 使用 Angular 将表单发布到 ASP.NET MVC ActionMethod

asp.net - 如何将 xml 文件添加到我的项目中?

c# - 从 Angular 2 到 ASP.NET ApiController 的 Http.post

c# - 如何强制浏览器使用版本控制重新加载缓存的静态文件?

c# - SignalR 1.0rc2 版本中未找到 Signalr IConnectionIdGenerator

javascript - 在 JavaScript 中输出 ASP.NET 模型