Asp.net:-是物理路径,但是应该使用虚拟路径

时间:2018-06-22 06:18:10

标签: c# asp.net excel virtual-path

我想从本地PC下载excel文件格式,所以我写了如下代码

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;
    }
}

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

所以在下载时我得到了错误消息

  

“ D:/ Name / CMP / CMP Excel模板/CMP_TEMPLATES.xlsx”是物理路径,但是希望使用虚拟路径。

我不知道它的预期路径。请建议

1 个答案:

答案 0 :(得分:1)

首先阅读文档:https://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

MapPath会基于相对路径或虚拟路径生成物理路径,因此给它指定物理路径没有任何意义。您已经有了物理路径,因此应该可以完全跳过该步骤。

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;
    }
}