views:

891

answers:

4

Hello all...

I simply want to write the contents of a TextBox control to a file in the root of the web server directory... how do I specify it?

Bear in mind, I'm testing this locally... it keeps writing the file to my program files\visual studio\Common\IDE directory rather than my project directory (which is where I assume root is when the web server fires off).

Does my problem have something to do with specifying the right location in my web.config? I tried that and still no go...

Thanks much...

protected void TestSubmit_ServerClick(object sender, EventArgs e)
    {
        StreamWriter _testData = new StreamWriter("data.txt", true);
        _testData.WriteLine(TextBox1.Text); // Write the file.
        _testData.Close(); // Close the instance of StreamWriter.
        _testData.Dispose(); // Dispose from memory.       
    }
+4  A: 
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
    StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt", true);
    _testData.WriteLine(TextBox1.Text); // Write the file.
    _testData.Flush();
    _testData.Close(); // Close the instance of StreamWriter.
    _testData.Dispose(); // Dispose from memory.       
}

Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.

Darthg8r
Thanks everyone. You guys rule.
Woody
+3  A: 
protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
    using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
    {
        w.WriteLine(TextBox1.Text); // Write the text
    }
}
Sean Bright
+2  A: 

Keep in mind you'll also have to give the IUSR account write access for the folder once you upload to your web server.

Personally I recommend not allowing write access to the root folder unless you have a good reason for doing so. And then you need to be careful what sort of files you allow to be saved so you don't inadvertently allow someone to write their own ASPX pages.

Spencer Ruport
+1  A: 
File.WriteAllText(Server.MapPath("~/data.txt), TextBox1.Text);
Guffa