Search code examples
c#asp.netexport-to-excel

How to avoid downloading files to the download folder and download to other specific folder only in c#


I am trying to convert the gridview to excel and downloading the excel sheet to my computer's specific folder in my c# application.

The problem is: The file is getting downloaded at both the places.The destination folder and also the download folder.

the code for this is:

private void ExportToExcel(GridView GrdView, string fname)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "inline;filename=" + fname + ".xls");
    Response.Charset = "";
    Response.ContentType = "application/OCTET-STREAM";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);
    GridView1.RenderControl(htmlWrite);
    string renderedGridView = stringWrite.ToString();
    File.WriteAllText(@"C:\\Users\abc\\Desktop\" + fname + ".xls", renderedGridView);
    Response.Write(stringWrite.ToString());
    Response.End();
}

How to avoid the files getting downloaded to the download folder? Please help! Thank you


Solution

  • The answer would be to pick one: either render the control to a string and output to Response OR WriteAllText. If you want to use the WriteAllText to save the file to a determined location, then perform the action and pop up a notification to the user that the file was saved.