Thursday, April 8, 2010

Downloading all type of files from Gridview

 protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
         try
    {
        int fileindex = (int)GridView1.SelectedValue;

         string dbPath = null;
   
        DataSet path = Download.GetresourcePath(fileindex);

        foreach (DataRow row in path.Tables["filepath"].Rows)
        {
            dbPath = string.Format("{0}", row["filepath"]);

         }

            string filePath = @dbPath;

             string fileName = Path.GetFileName(filePath);

            System.IO.Stream stream = null;

            stream = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            long bytesToRead = stream.Length;
            Response.ContentType = "application/octet-stream";

             Response.AddHeader("content-Disposition", "attachment; filename=" + fileName);

              while (bytesToRead > 0)
            {
                if (Response.IsClientConnected)
            {
                byte[] buffer = new Byte[10000];
                int length = stream.Read(buffer, 0, 10000);
                Response.OutputStream.Write(buffer, 0, length);
                Response.Flush();
                bytesToRead = bytesToRead - length;
            }
            else
                {
                    bytesToRead = -1;

                }
        }
        }
        catch (Exception ex)
        {

        }

        }

No comments:

Post a Comment