mvc web api中文件的真实物理路径

时间:2015-07-15 06:31:09

标签: c# asp.net-mvc-4 asp.net-web-api

我正在使用MVC web api构建一个示例应用程序。我从POST请求中获取文件名。如果我使用下面的代码来获取文件的物理路径,它将返回应用程序文件夹的路径而不是我的其他驱动器中的文件路径(例如D:驱动器)

HttpContext.Current.Server.MapPath("/~" + fileName);

3 个答案:

答案 0 :(得分:2)

请使用以下声明

HttpContext.Current.Request.PhysicalApplicationPath + "/" + fileName

答案 1 :(得分:1)

我建议你这样做:

1. Create a application setting:

      <appSettings >
        <add key="FolderPath" value="D:\"/>
      </appSettings>
2. Change your code:
    string root= ConfigurationManager.AppSettings["FolderPath"].ToString();
    var physicalFilePath =root + fileName;

答案 2 :(得分:0)

HttpContext.Current.Server.MapPath总是为您提供从目录根目录到您正在处理的当前目录的绝对路径。

如果您希望从特定目录中读取文件:

  • 确定文件可用的常用路径,例如D:\
  • 将此路径放在带有名称的应用设置下的web.config文件中,例如“FileDirectory”。
  • FileDirectory(从appsettings中读取)和您的文件的路径结合起来,比如Path.Combine(FileDirectory, file)

您将获得该文件。