2

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.

1
  • Do you want an absolute path or absolute url? Commented Jul 19, 2009 at 14:04

2 Answers 2

8

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

In ASP.Net Core MVC 6 This can be done as,

public class YourController : Controller
{
    private readonly IWebHostEnvironment env;

    public YourController(IWebHostEnvironment env)
    {
        this.env = env;
    }

    // Your action method for handling file upload
    public IActionResult UploadFile(IFormFile imgFile)
    {

        var virtualFilePath = Path.Combine("data/products/imgs", Guid.NewGuid().ToString() + Path.GetExtension(imgFile.FileName));


        var webRootPath = env.WebRootPath;

       
        var imgFilePath = Path.Combine(webRootPath, virtualFilePath);

        // atomic transaction
        using (var stream = new FileStream(imgFilePath, FileMode.Create))
        {
            imgFile.CopyTo(stream);
        }

       

        return RedirectToAction("UploadSuccess");
    }


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.