1

I can't get this asp.net page do write to a file. I was following this guide. I am not sure what i am doing wrong because i can use this button to change label text, but not to print "Hello World" into a text file in the same directory.

<%@ 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>

enter image description here

Some_Dude
  • 309
  • 5
  • 21
  • Do you have write permissions for the folder you're trying to write to? – Nick B Jul 02 '18 at 17:59
  • Yeah, i made the text file with my computer. I can open it in notepad and save text into the file, so I assume the web browser can do the same. – Some_Dude Jul 02 '18 at 18:04
  • 4
    The web browser wouldn't be doing the file manipulation. It'd be the web server. – mason Jul 02 '18 at 18:07
  • It seems to be a syntax error since its saying invalid element name. If i replace the code in the middle of the button function with something that changes the text on the label then it works. It seems the problem is the file writting code. – Some_Dude Jul 02 '18 at 18:09
  • this is definitely something best left to be handled server side not client side – Salim Proctor Jul 02 '18 at 18:17

1 Answers1

1

The problem is probably this error "The type or namespace name 'StreamWriter' could not be found". That's because there is no using System.IO present. To fix this write out the complete NameSpace of the StreamWriter.

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

Or add it to the single page

<%@ Import Namespace="System.IO" %>
VDWWD
  • 35,079
  • 22
  • 62
  • 79