asp.netrelative-pathabsolute-path

ASP.NET: Path.Combine with relative paths


I'm trying to convert "~/Uploads/Images/" to an absolute path I can create a FileStream from. I've tried VirtualPathUtility and Path.Combine but nothing seems to give me the right path. The closest I got was VirtualPathUtility.ToAppRelative, but that was just the file's location as a direct child of C:.

There must be a way to do this.


Solution

  • You are looking for the MapPath method.

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

    Use it together with Path.Combine to create a file path:

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