【问题标题】:Write to a file C# ASP.net on button click单击按钮时写入文件 C# ASP.net
【发布时间】:2018-12-10 23:48:11
【问题描述】:

我无法让这个 asp.net 页面写入文件。我正在关注这个guide。我不确定我做错了什么,因为我可以使用此按钮更改标签文本,但不能将“Hello World”打印到同一目录中的文本文件中。

<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(Object sender, EventArgs e) 
{ 
        using (StreamWriter w = new StreamWriter(Server.MapPath("~/Saved Layouts.txt"), true))
        {
            w.WriteLine("Hello World"); // Write the text
        }
}
</script>
<html>
<head>
  <title>Single-File Page Model</title>
</head>
<body>
  <form runat="server">
    <div>
       <asp:Label id="Label1" 
         runat="server" Text="Label">
       </asp:Label>
       <br />
       <asp:Button id="Button1" 
         runat="server" 
         onclick="Button1_Click" 
         Text="Button">
      </asp:Button>
    </div>
  </form>
</body>
</html>

【问题讨论】:

  • 您对要写入的文件夹有写入权限吗?
  • 是的,我用我的电脑制作了文本文件。我可以在记事本中打开它并将文本保存到文件中,所以我假设网络浏览器也可以这样做。
  • 网络浏览器不会进行文件操作。它是网络服务器。
  • 这似乎是一个语法错误,因为它说元素名称无效。如果我用改变标签上文本的东西替换按钮功能中间的代码,那么它就可以工作。看来问题出在文件编写代码上。
  • 这绝对是最好留给服务器端而不是客户端处理的事情

标签: c# asp.net


【解决方案1】:

问题可能是这个错误“找不到类型或命名空间名称'StreamWriter'”。那是因为没有using System.IO 存在。要解决此问题,请写出 StreamWriter 的完整 NameSpace。

using (System.IO.StreamWriter w = new System.IO.StreamWriter(Server.MapPath("~/Saved Layouts.txt"), true))
{
    w.WriteLine("Hello World"); // Write the text
}

或者添加到单页

<%@ Import Namespace="System.IO" %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多