1

I'm trying to seed my database with an image. I'm able to do this successfully using an absolute path, however this won't work as a permanent solution.

 Image = File.ReadAllBytes(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg"),

How could I get the same path so resolve. Using something like

~\Images\Ferrari488.jpg

Any help would be appreciated.

2
  • Have you looked at Path.Combine and stackoverflow.com/questions/5203945/… ? Commented May 29, 2019 at 4:15
  • Oh the good problem with MVC applications. ~ is supposed to be pointing to wwwroot and yet it doesn't? VS has suddenly decided to use IIS Express directory instead of Project directory as home path, no? Try printing WorkingDirectory variable from Environment and it will tell you what's going on. Commented May 29, 2019 at 4:32

1 Answer 1

2

For getting only file name from a path you can use Path.GetFileName('path'); which in your case you can get the file name first as:

var fileName = System.IO.Path.GetFileName(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg");
//filename will now only contain: Ferrari488.jpg

//Now let's concatenate it with ~/Images/
var storingPath= "~\Images\" + fileName;

Now for the absolute path, try using Server.MapPath("~") which returns the physical path to the root of the application.

So in your case if you want to get the absolute path for ~\Images\Ferrari488.jpg then it will look like: Server.MapPath("~\Images\Ferrari488.jpg"); or System.Web.HttpContext.Current.Server.MapPath("~\Images\Ferrari488.jpg");

OR

var absolutePath = System.Web.HttpContext.Current.Server.MapPath(storingPath);
Image = File.ReadAllBytes(absolutePath);
Sign up to request clarification or add additional context in comments.

3 Comments

I still need the File.ReadAllBytes so I can convert the image to bytes to store it in the DB. Will Server.MapPath do that? I can't get the "Server" to resolve any idea what the using statement should be?
Thank you for your response, i have now got it working. I used, var absolutePath = System.Web.HttpContext.Current.Server.MapPath(@"~\Images\"); Then, Image = File.ReadAllBytes(absolutePath + "Ferrari488.jpg"), Once again Thanks for the help.
absolutePath + "Ferrari488.jpg" Do not do that. Use Path.Combine.

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.