Sunday, March 25, 2012

File Upload to save file to server location


Below code help us to create/move files from one folder to another or from client machine to server machine using c#.

Below is the sample folder structure

Folder Structure :

If above structure is used then no need to read it from web.config file. 
Attachment folder is a folder in which files are stored.

.aspx file snippet for File upload control:
<td align="center" >
        <span>Scanned Documents</span>
        <asp:FileUpload ID="fuScanedDocument" runat="server" /><span> (File Size Limit : 2 MB)</span>
</td>



Code File:

protected void btnUpload_Click(object sender, EventArgs e)
    {

        if (fuScanedDocument.HasFile)
        {
            if ((fuScanedDocument.PostedFile != null) && (fuScanedDocument.PostedFile.ContentLength > 0))
            {
                
//Below code gets the server location
                string SaveLocation = Server.MapPath("Attachments"); 
                try
                {
                    if (Directory.Exists(SaveLocation)
                    {
                        string p = Server.MapPath("Attachments"

// Below code saves the file on specified location
                        fuScanedDocument.PostedFile.SaveAs( SaveLocation   );
                                               
                    }
                }
             
           }
       
        }
       
    }

No comments:

Post a Comment