Uploading & Downloading Files to server In ASP.NET

2010-05-23

Here is the code for uploading files to server in asp.net

Uploading files
---------------------



string savedPath = SaveFileToServer(fupExcelUpload);

private string SaveFileToServer(FileUpload fupExcelUpload)

{

try

{

string file = Path.GetFileName(fupExcelUpload.PostedFile.FileName);

if (!Directory.Exists(Server.MapPath("~/User_Data/TBD/BOQTenderAttachments/")))

{

Directory.CreateDirectory(Server.MapPath("~/User_Data/TBD/BOQTenderAttachments/"));

}

string filePathTemp = "~/User_Data/TBD/BOQTenderAttachments/";

ViewState["DocumentName"] = file;

Random rnd = new Random();

string fileName = rnd.Next().ToString() + "_" + Path.GetFileName(fupExcelUpload.PostedFile.FileName);

FileInfo fileInfo = new FileInfo(fileName);

string extention = fileInfo.Extension;

fupExcelUpload.PostedFile.SaveAs(Server.MapPath(filePathTemp + fileName));

ViewState["DocumentPath"] = filePathTemp + fileName;

return ViewState["DocumentPath"].ToString();

}

catch (Exception ex)

{

return "";

}

}




Downloading file from server
--------------------------------
protected void lnkAttachFilename_Click(object sender, EventArgs e)

{

try

{

LinkButton lnk = (LinkButton)sender;

GridViewRow _GridViewRow = (GridViewRow)lnk.NamingContainer;

Label LblFile = _GridViewRow.FindControl("lblAttachFilename") as Label;

string[] Filename = LblFile.Text.Split('/');

string filePath = Server.MapPath("~/User_Data/TBD/BOQTenderAttachments/" + Filename[Filename.Length - 1]);

DownloadFileFromServer(filePath, Filename[Filename.Length - 1]);

}

catch (Exception ex)

{

Alert("HRM_INAVLID_FILE_PATH");

}

}

private void DownloadFileFromServer(string FilePath,string FileName)

{

try

{

FileInfo ResInfo = new FileInfo(FilePath);

if (!ResInfo.Exists)

{

File.Create(FilePath);

}

Response.Clear();

Response.AddHeader("content-disposition", "attachment;filename=" + FileName);

Response.WriteFile(FilePath);

Response.End();

//File.Delete(FilePath);

}

catch (Exception ex)

{

}

}




NOTE: Downloading file is shown as a file name inside a gridview in a linkbutton

0 comments: