net/C# application I have list of items.
In the code behind: I want to assign a picture from my local resources for each item. the items name and the picture names are the same. The pictures are all in a "image" folder in my project.
Example of how I assign a picture to an item:
Item1.PictureUrl = "images/items/" + item1.Name + ".jpg";
I have items that don't have pictures. I want to assign for them a default picture.
I tried to check if the picture exists using this:
foreach(ObjectItem item in ListOfItems)
{
if(File.Exists("images/items/"+item.Name+".jpg"))
item.PictureUrl = "images/items/"+item.Name+".jpg";
else
item.PictureUrl= "images/Default.jpp";
}
But the File.Exists method is always returning false, even if the picture exist. I also tried to use '\' instead of '/' but didn't work
How can I do it?
Thank you for any help
function imageExists(url, callback) { var img = new Image(); img. onload = function() { callback(true); }; img. onerror = function() { callback(false); }; img. src = url; } // Sample usage var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png'; imageExists(imageUrl, function(exists) { console.
To check whether the specified file exists, use the File. Exists(path) method. It returns a boolean value indicating whether the file at the specified path exists or not.
You need to convert the relative file path into a physical file path in order for File.Exists to work correctly.
You will want to use Server.MapPath to verify the existence of the file:
if(File.Exists(Server.MapPath("/images/items/"+item.Name+".jpg")))
Also, when you use Server.MapPath, you should usually specify the leading slash so that the request is relative to the web application's directory.
If you don't provide the leading slash, then the path will be generated relative to the current page that is being processed and if this page is in a subdirectory, you will not get to your images folder.
var path = $@"C:\Fotos\Funcionarios\1.Png";
FileInfo file = new FileInfo(path);
if (file.Exists.Equals(true))
{
//faz algo
}
.Net Core Solution
1- Write this at the top of your View (Injecting IHostingEnvironment here);
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
2- Write this to the place of image(Doing existence check);
var path = System.IO.Path.Combine(hostingEnv.WebRootPath, "MyFolder", "MyImage.jpg");
if (System.IO.File.Exists(path))
{
<img class="img-fluid" src="~/MyFolder/MyImage.jpg" alt="">
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With