tags:

views:

161

answers:

7

In C# ASP.Net, I would like to create and save a text file to a server. This will be happening daily (by a user action, not scheduled).

I would like the location to not be in the application path but in a separate folder (for this question, lets say the folder is off the root).

I am new to this site and if this question is too "open", feel free to let me know.

Thanks for your assistance.

A: 

Here is an example:

// Pass a path and filename to the StreamWriter's
// constructor.  The path must already exist but the
// file will be created if it does not already exist.
using (TextWriter tw = new StreamWriter("c:\\foo\\bar.txt"))
{
    tw.WriteLine("hello world");
}
Andrew Hare
+1  A: 

I don't see any specific issue in doing so. You just need to make sure the user running ASP.NET is granted the required permissions to write to the output folder.

Mehrdad Afshari
+2  A: 

You can use System.IO classes to save to a file on the local filesystem.

using(var w = new StreamWriter(filename))
{
    w.WriteLine("Hello world!");
}
Arjan Einbu
+1  A: 

You'll want to use Server.MapPath to get to the physical path of your folder.

    using (TextWriter tw = new StreamWriter(Server.MapPath("Folder1")))
 {
  tw.WriteLine("hello world"); 
 }
Joshua Belden
+2  A: 

Just to add on what others have said, when writing to a file in a multi-threaded application, you need to synchronize the access to this resource. You could use ReaderWriterLockSlim to achieve this:

// Make this a static field
ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

_lock.EnterWriteLock();
try
{
    File.WriteAllText(@"c:\test.txt", "some info to write");
}
finally
{
    _lock.ExitWriteLock();
}
Darin Dimitrov
+3  A: 

One good practice to follow is to use a web.config app setting key to define the output path of your application.

You'd use the ConfigurationManager.AppSettings class for retrieving values from a web.config. You can read how to do this here:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx

Dan Herbert
+3  A: 

I agree with DanHerbert. Put the path in web.config and make sure the permissions for the folder are correct.

Also, make sure that path is not on the C drive. That way, if something goes wrong, or if the site is attacked, the c drive won't fill up and crash the server.

Be careful with the permissions; even a simple text file can be dangerous if a hacker can muck with the path somehow. Think about someone overwriting the server's hosts file, for example.

R Ubben