Sunday, June 20, 2010

Simple File Upload in C# .Net



Here are a few simple steps you can follow to upload files in C# ASP.Net using the File Upload Control in Visual Studio:
Step 1:
* Create the file upload control in the design view. The ID of my control is "File1".

Step 2:
*Here is the code to upload a file.


protected  string   uploadFile(string userid, string oldFileLocation)
{
    if (File1.PostedFile != null && File1.PostedFile.ContentLength>0)
    {
        string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
        string SaveLocation = Server.MapPath("Folder") + "\\" + userid + "_" + fn;
 
        if (!fn.EndsWith(".doc") && !fn.EndsWith(".pdf") && !fn.EndsWith(".docx"))
        {
            return "Invalid File Type!";
        }
 
        if (!string.IsNullOrEmpty(oldFileLocation))
        {
            System.IO.File.Delete(oldFileLocation);
        }
 
        File1.PostedFile.SaveAs(SaveLocation);
        return "File Uploaded!";
    }
}



Note:
*I have used "userid" to ensure that uploaded files have unique names.
*I have created a folder "Folder" to save files into.
*I have added a check for the format of the uploaded file. You can vary the valid file type.
*I have also done a check to delete the existing file for that user.

No comments:

Post a Comment