Translate

Friday 29 May 2015

Download All type of File in Web

protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            string FilePath = txtFileLogPath.Text.Trim();
            string fileName = Path.GetFileName(FilePath);
            string fileExtension = Path.GetExtension(FilePath);
            if (!string.IsNullOrEmpty(fileExtension))
            {
                System.IO.FileStream fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, (int)fs.Length);
                fs.Close();
                Response.ContentType = "application/x-unknown/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName);
                try
                {
                    if (bt != null)
                    {
                        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
                        stream1.Write(bt, 0, bt.Length);
                        Response.BinaryWrite(bt);
                        Response.Flush();
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    txtFileLogPath.Text = "";
                    Display(this.GetType(), "Error", "Error Occured");
                }
                finally
                {
                    Response.End();
                    txtFileLogPath.Text = "";
                }
            }
            else
            {
                Display(this.GetType(), "Warning", "Please enter correct path with extension");
                txtFileLogPath.Text = "";
            }
        }
        private void Display(Type t, string errorCaption, string errorMessage)
        {
            string scriptError = "<script>alert('" + errorMessage + "');</script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), errorCaption, scriptError);
        }