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.
2 replies on “ASP.NET C# – Grabbing a posted file and save to disk”
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).
LikeLike
yeah, that is good if you have a interface, for my purpose it was a file uploaded programatically behind the scenes. thanks for the comment though
LikeLike