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

ASP.NET:路径。与相对路径结合

  •  2
  • Echilon  · 技术社区  · 15 年前

    我正在尝试将“~/uploads/images/”转换为可以从中创建文件流的绝对路径。我尝试过virtualpathutility和path.combine,但似乎没有什么能给我正确的路径。我最近得到的是virtualpathutility.toapprelative,但这只是作为c:的直接子级的文件位置。

    一定有办法做到这一点。

    1 回复  |  直到 15 年前
        1
  •  8
  •   Fredrik Mörk    15 年前

    你在找 MapPath 方法。

    // get the path in the local file system that corresponds to ~/Uploads/Images
    string localPath = HttpContext.Current.Server.MapPath("~/Uploads/Images/");
    

    与路径一起使用。合并以创建文件路径:

    string fileName = Path.Combine(
                          HttpContext.Current.Server.MapPath("~/Uploads/Images/"),
                          "filename.ext");
    using (FileStream stream = File.OpenRead(fileName))
    {
       // read the file
    }