Wednesday, March 30, 2016

Code to search CSV files and provide user the option to download them

You have some CSV files stored in a folder on your server and you want to let the user download each separately. You will need a ASP.NET placeholder (ID="Downloads") on your UI.

 private void CheckForDownloadFiles(string filePath)
    {
        DirectoryInfo d = new DirectoryInfo(filePath);  
        FileInfo[] Files = d.GetFiles("*.csv"); //Getting CSV files
        Downloads.Controls.Clear();
        string str = ""; int i = 0;
        foreach (FileInfo file in Files)
        {
            str = str + ", " + file.Name;
            i++;
            CreateLinkButtonAndLabel(file.Name,i, filePath);
        }
    }


private void CreateLinkButtonAndLabel(string fileName, int count, string filePath)
    {

        Downloads.Controls.Add(new LiteralControl("<br />"));
        LinkButton newDownload = new LinkButton();
        newDownload.ID = "DownloadBtn"+count;
        newDownload.CommandArgument = filePath+fileName;
        newDownload.Click += new EventHandler(DownloadCSV);
        newDownload.CssClass += "btn btn-success btn-xs";
        newDownload.Text = "<img src='../Images/icons/csv-file.gif' alt='Download CSV File' /> Download CSV";
        Downloads.Controls.Add(newDownload);
        Label label = new Label();
        label.ID = "DownloadLabel" + count;       
        label.Text = " "+fileName+" ";
        Downloads.Controls.Add(label);
}


protected void DownloadCSV(object sender, EventArgs e)
    {

        LinkButton btn = (LinkButton)sender;
        string fullFilePath = btn.CommandArgument;
        if(fileName.Contains("csv"))
            Response.Redirect(fullFilePath);
  }

This will create a button and display the name of your file next to it:





No comments:

Post a Comment