Reputation: 73
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.
Upvotes: 1
Views: 2277
Reputation: 425
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);
Upvotes: 2