Uploading a file to your .NET Web Application

By xerocube | January 4, 2007

I have been working on a skunk works project at my office for the past few days and have been struggling with one small detail — uploading a file to a specific folder within my project path. I wanted to store the file in a relative path, in case I had to move the application to a different server. While this may be a common thing for many code ninjas, I’m relatively new to this and, as such, am excited at my discovery. I’ve found the Request.PhysicalApplicationPath HTTP attribute contains the physical application of the running application, which means I can determine my “relative” filepath.

Below is a helper function I have that takes an HTTP Encoded file from an ASP .NET FileUpload (FileUpload1) control, determines my “relative” file path, saves the (or overwrites an existing) file on the web server, and then returns a string containing the physical path to the file on the server.

string SaveFile(HttpPostedFile file)
{
// Save the uploaded file to an “Results” directory that already exists in the file system of the
// currently executing ASP.NET application. Creating an “Results” directory isolates uploaded
// files in a separate directory. This helps prevent users from overwriting existing application files by
// uploading files with names like “Web.config”.
string saveDir = @”\Results\”;

// Get the physical file system path for the currently
// executing application.
string appPath = Request.PhysicalApplicationPath;

// Specify the path to save the uploaded file to.
string savePath = appPath + saveDir + Server.HtmlEncode(FileUpload1.FileName);

// Call the SaveAs method to save the uploaded
// file to the specified directory.
FileUpload1.SaveAs(savePath);

return (savePath);
}

It’s amazing what you can find when you spend time researching the MSDN library for assistance.

Topics: Code | No Comments »

Comments

Archives

Blogroll

RockinMedia