-3

I want to download an excel file format from my local PC, So I wrote my code as below

protected void btnDownloadExcelTemp_Click(object sender, EventArgs e)
{
    try
    {
        string strFileFormat = System.Configuration.ConfigurationManager.AppSettings["FormateFilePath"].ToString();
        string strFilePath = HttpContext.Current.Server.MapPath(strFileFormat + "/CMP_TEMPLATES.xlsx");
        HttpResponse response = HttpContext.Current.Response;
        response.Clear();
        response.AppendHeader("content-disposition", "attachment; filename=" + "CMP_TEMPLATES.xlsx");
        response.ContentType = "application/octet-stream";
        response.WriteFile(strFilePath);
        response.Flush();
        response.End();
    }
    catch (Exception)
    {            
        throw;
    }
}

and strFileFormat is <add key="FormateFilePath" value="D:/Name/CMP/CMP Excel Template"/>

So while downloading I am getting error as

'D:/Name/CMP/CMP Excel Template/CMP_TEMPLATES.xlsx' is a physical path, but a virtual path was expected.

I dont know what path its expecting. Please suggest

Nad
  • 4,605
  • 11
  • 71
  • 160
  • `strFileFormat = "~/Name/CMP/CMP Excel Template/CMP_TEMPLATES.xlsx"` is enough i think. Try `response.WriteFile(strFileFormat );` – Rishi Malviya Jun 22 '18 at 06:23
  • Duplicate of [Server MapPath - Physical given, virtual path expected](https://stackoverflow.com/questions/5039725/server-mappath-physical-path-given-virtual-path-expected) – H.Mikhaeljan Jun 22 '18 at 06:23
  • @RishiKalal: that's what I tried – Nad Jun 22 '18 at 06:25
  • Possible duplicate of [Server.MapPath - Physical path given, virtual path expected](https://stackoverflow.com/questions/5039725/server-mappath-physical-path-given-virtual-path-expected) – Jon P Jun 22 '18 at 06:27

1 Answers1

1

Start by reading the doc: https://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx .

MapPath generates a physical path based on a releative or virtual path, so it makes no sense to give it a physical path. You already have the physical path so you should be able to completely skip that step.

protected void btnDownloadExcelTemp_Click(object sender, EventArgs e)
{
    try
    {
        string strFileFormat = System.Configuration.ConfigurationManager.AppSettings["FormateFilePath"].ToString();
        string strFilePath = strFileFormat + "/CMP_TEMPLATES.xlsx";
        HttpResponse response = HttpContext.Current.Response;
        response.Clear();
        response.AppendHeader("content-disposition", "attachment; filename=" + "CMP_TEMPLATES.xlsx");
        response.ContentType = "application/octet-stream";
        response.WriteFile(strFilePath);
        response.Flush();
        response.End();
    }
    catch (Exception)
    {            
        throw;
    }
}
Jon P
  • 19,442
  • 8
  • 49
  • 72