Here are the simple two lines of code:
public static void RemoveCoverImageForProduct(int productId)
{
using (var productRepository = new EfProductRepository())
{
var product = productRepository.FindById(productId);
var coverFolderPath = HttpContext.Current.Server.MapPath(@"~/");
var filePath = Path.Combine(coverFolderPath, product.CoverImagePath);
if (File.Exists(filePath))
File.Delete(filePath);
}
}
Server.MapPath() is returning:
C:\Users\Sergio\Desktop\MyApp\MyApp.WebUI\
product.CoverImagePath is returning:
/Public/products/buscar.jpg
The result of running Path.Combine on both of them, meaning the value of filePath after running is:
/Public/products/buscar.jpg
What I’m expecting is this:
C:\Users\Sergio\Desktop\MyApp\MyApp.WebUI\Public\products\buscar.jpg
Any ideas why this isn’t working as I expect it to?
The rules for the second argument of
Path.CombineareThe slash in
product.CoverImagePathis a root, which is whyPath.Combineis returningAssuming you know that it begins with a slash, you can remove it and pass that into
Path.Combine:If you’re unsure, use a conditional: