Uploading a file using ASP.Net
April 10th, 2008 admin Posted in asp.net, c#, development |
I know there are loads of articles related to uploading a file usin ASP.Net application. But still there is my method of doing that. Usually while creating a web application all my pages extend one base class but not the Page class. I always create some base class which extends the Page, so I could add some basic functionality and it and use it on any page I want. So the UploadFile procedure would on the methods of my base page class.
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.IO; public class MyPage : Page { .......... // strUploadFolder - full path to the folder in which we are gonna store the file (i.e c:\savehere) // strFileName - return parameter, that will store upaded file's name // function returns true if uploading has been successfull, otherwise we get false protected bool UploadFile(HtmlInputFile fileinput, string strUploadFolder, ref string strFileName) { HttpPostedFile myFile = fileinput.PostedFile; int nFileLen = myFile.ContentLength; strFileName = string.Empty; if (nFileLen > 0) { byte[] myData = new byte[nFileLen]; myFile.InputStream.Read(myData, 0, nFileLen); strFileName = Path.GetFileName(myFile.FileName); try { if (!Directory.Exists(strUploadFolder)) Directory.CreateDirectory(strUploadFolder); using (FileStream newFile = new FileStream(Path.Combine(strUploadFolder, strFileName), FileMode.Create)) { newFile.Write(myData, 0, myData.Length); newFile.Close(); } } catch (Exception ex) { throw ex; } return true; } else return false; } .......... }
Leave a Reply