Monday, October 15, 2012

Download file using linq from the GridView asp.net 4.0

I am going to tell how to download files using a gridview in asp.net. I have used C# as my language.
In .aspx page:

                        
                        
                            
                                
                                    
                                
                            
                        
                        
                        
                        
                        
                        
                        
                        
                        
                        
                        


Bind GridView using Linq:
private void BindGridDownloadFile()
        {
         CIPEntities _context = new CIPEntities();
            _context = new CIPEntities();
            List SpritsData = new List();
            SpritsData = _context.tbl_SpiritsSyndicateData.Where(c => c.CategoryId == 1).ToList();
            GridView1.DataSource = SpritsData;
            GridView1.DataBind();
        }
Define the event "GridView1_RowCommand" as follows:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "OpenFile")
            {

                string name = (string)e.CommandArgument;
                string fullFilePath = Server.MapPath("~/Content/Upload/" + name); //might be you need to change this statement if file does not exist within application folders

                System.IO.FileInfo fileInfo = new System.IO.FileInfo(fullFilePath);
                if (fileInfo.Exists)
                {
                    this.Response.Clear();

                    this.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                    this.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    this.Response.ContentType = "application/octet-stream";
                    //this.Response.TransmitFile(fileInfo.FullName);
                    this.Response.BinaryWrite(File.ReadAllBytes(fileInfo.FullName));
                    this.Response.End();
                }
                else
                {
                    Response.Write("NO FILE PRESENT");
                }
            }

        }

If need project code then feel free email me please.
I hope you like this article. Enjoy!

No comments:

Post a Comment