简体   繁体   中英

How do I write a text file from within a C# ASP.NET page?

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]}

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

Edit

if Request.Form["message"] is coming in empty. Make sure that:

  1. there's a text input element named message
  2. there's no other element with the same name attribute
  3. the input element is inside the form tag with runat=server attribute
  4. you are posting back the page instead of issuing a GET request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM