ASP.NET C# – Grabbing a posted file and save to disk

Sometimes you want to grab a file posted to a page, maybe an image upload or other file upload

HttpFileCollection logFiles = Request.Files;
string path = System.Configuration.ConfigurationManager.AppSettings[“LogPath”];
if (logFiles.Count > 0)
{
HttpPostedFile logFile = logFiles.Get(0);

logFile.SaveAs(path + System.Guid.NewGuid().ToString() + “.log”);
}

As you can see, I am setting the log path from the config. The reason for this is, the path to save to is absolute, something like c:blahblahwhatever

I am saving the file with a GUID as the file name, for uniqueness, but you can grab the name form the file object as well. There are some other gotchas. 4MB limit on files, unless you tweak the HTTP runtime in the web.config, also, you need to make sure that Network Service or ASPNET user has rights to modify the log folder you are writing too. Otherwise you can impersonate a user in the web.config, and make sure that user has rights.

Advertisements

2 thoughts on “ASP.NET C# – Grabbing a posted file and save to disk”

  1. You may also want to take a look at an upload management component that will provide scalability and progress feedback to the user in realtime. That way you don’t have to worry about the normal ASP.NET limitations and your users can see a progress display so they can monitor the upload. If you’re interested, check out my SlickUpload ASP.NET upload component (http://krystalware.com).

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s