Reputation: 2460
I'm coming to C# ASP.NET from Ruby and PHP, and I'm enjoying some elements of it but am finding certain things difficult to achieve. It's a bit different to get my head around, and I'd really appreciate it if someone could help me get this bit up and running.
I am trying to take some text sent in a POST request, HTML-escape it, and then write it to a text file.
So I look it up, read a little, and try:
<%
System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath(@"./messager.txt"));
file.WriteLine(Request.Form["message"]);
file.Close();
%>
Not doing the HTML-escaping yet, just trying to actually write to the text file.
This doesn't work, though; it throws no error that I can see, but just does nothing, the text file isn't written to at all. I've researched the methods and can't really figure out why. I would really love some help.
If it helps, here is working Ruby code for what I am trying to do:
File.open "messager.txt", "w" {|f| f.puts h params[:message]}
Upvotes: 1
Views: 3260
Reputation: 14820
You have to provide a virtual path relative to the web app when using Server.MapPath
using the special character ~
which is a shortcut to the web app root directory. Now, the simplest way to do it is a follows...
System.IO.File.WriteAllText(Server.MapPath("~\messager.txt"), Request.Form["message"]);
this is assuming that the request actually contains the "message" form variable. Note that this approach will create a new file if it doesn't exist or will override it if it does exist.
However, in ASP.NET Web Forms we usually use server controls such as a TextBox
, if when posting the page the message is set to a text box, then a better way to retrieve this message in OOP-style would be...
TextBox_ID.Text;
where TextBox_ID
is the id of the TextBox
if Request.Form["message"]
is coming in empty. Make sure that:
message
name
attributeform
tag with runat=server
attributeUpvotes: 2