代码之家  ›  专栏  ›  技术社区  ›  Jan

在ASP.NET MVC中访问服务器上的文件

  •  3
  • Jan  · 技术社区  · 14 年前

    在我的ASP.NET MVC应用程序中,我正在生成excel报表,我有一个模板文件,可以复制和修改。此模板文件放在我的解决方案的文件夹中。我想使用它如下:

    string templatePath = @"\Templates\report.xlsx";
    
    using (var template = File.OpenRead(templatePath)) {
      // Copy template and process content
    }
    

    但这段代码生成了一个异常

     Couldnot find a part of the path 'C:\Templates\report.xlsx'.
    

    我应该如何引用这个文件?

    string templatePath = @"~\Templates\report.xlsx";
    

    但结果是

    Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Templates\report.xlsx'.
    

    但是,当我使用绝对路径时,它确实有效,但这对我的生产服务器没有意义。

    2 回复  |  直到 14 年前
        1
  •  8
  •   Jess    14 年前

    我相信你会用普通的ASP.NET方式,假设模板是你的web应用程序中的一个目录。

    string templatePath = @"~\Templates\report.xlsx";
    
    using (var template = File.OpenRead(Server.MapPath(templatePath))) {
      // Copy template and process content
    }
    
        2
  •  0
  •   CatDadCode    14 年前

    string templatePath = Server.MapPath("~/Templates/report.xlsx"); //Note the forward slashes instead of backslashes.
    
    using (var template = File.OpenRead(templatePath)) {
      // Copy template and process content
    }
    

    这将虚拟目录路径映射到服务器上的完整路径。