Monday, October 13, 2008

Using C# FileUpload in Visual Studio 2005

I can usually find the right item to use, but not always the correct syntax to use it. I did find the C# syntax for the FileUpload tool pretty quickly though, and thought I'd share.

if (Image1Upload.HasFile)
{
try
{

//change label to show upload starting
statusLbl.Text = "Uploading File " + Image1Upload.FileName;

//get current working directory on server and store as currentPath
String currentPath = Server.MapPath(".")
//create new path by combining current path and upload file name
String uploadPath = Path.Combine(currentPath, Image1Upload.FileName);
//upload file to your desired upload path
Image1Upload.SaveAs(uploadPath);

//change label to show successful upload
statusLbl.Text = "File Successfully Uploaded";
}
catch
{
statusLbl.Text = "Unable to save the file";
}
}
else
{
statusLbl.Text = "You have to select a file to upload";
}


This has two dependencies, which are a FileUpload named Image1Upload, and a Label named statusLbl. Image1Upload is what's actually used for the file, while statusLbl is optional and is just used to display the status to the end user so they know whether the upload worked or not. You can also add folders to the currentPath variable in order to put the uploaded file elsewhere, for example:

//put the file in a folder called images
String currentPath = Server.MapPath(".") + "\\images\\";

You need to use double backslashes because it's the escape character. Also, in order to use the Path.Combine() command, you must include using System.IO; in your project.

The original post, along with VB instructions too, can be found here.

No comments: