Monday, October 3, 2011

to Upload and download a file in the appn, asp.net

write this in a asp botton after browse the file using file upload button: 

if (FileUpload1.HasFile)
            {
                string strFileExtension = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);

                if (strFileExtension.ToUpper() == ".DOC" || strFileExtension.ToUpper() == ".DOCX" || strFileExtension.ToUpper() == ".TXT" || strFileExtension.ToUpper() == ".XLS" || strFileExtension.ToUpper() == ".XLSX" || strFileExtension.ToUpper() == ".PDF" || strFileExtension.ToUpper() == ".JPG" || strFileExtension.ToUpper() == ".JPEG" || strFileExtension.ToUpper() == ".PNG")
                {
                    string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.FileName);
                    string fn = fileNameWithoutExtension + "" + txtMRNNO.Text + "_" + DateTime.Now.ToString().Replace("/", string.Empty).Replace(" ", string.Empty).Replace(":", string.Empty) + "" + strFileExtension;
                    string SaveLocation = Server.MapPath("~/MedicalRecords/Uploads/") + fn;
                    FileUpload1.PostedFile.SaveAs(SaveLocation);
                    FileUpload1.Visible = false;
                    Label1.Text = fn;
                    imgAttachmentsSave.Focus();
                    btnUpload.Visible = false;
                }




for dowloading:


if (e.CommandName == "Download")
            {
                int Count = Convert.ToInt32(e.CommandArgument);
                //GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
                Label lblFileName = new Label();
                lblFileName = gvAttachments.Rows[Count].FindControl("lblFileName") as Label;

                string filename = Server.MapPath("Uploads/" + "" + Convert.ToString(lblFileName.Text));
                FileInfo fileInfo = new FileInfo(filename);
                if (fileInfo.Exists)
                {
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
                    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.Flush();
                    Response.WriteFile(fileInfo.FullName);
                    Response.End();
                }
            }