Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if resource file exists

Tags:

c#

wpf

I have an image file in my project's folder in visual studio and it is set to build action "resource" so it is included in my exe file.

I can link to this file in xaml no problem, for example <Image Source="images/myimage.png"> and it works.

But if I try to check the existence of the file, with File.exists("images/myimage.png") it always returns false. What am i doing wrong here?

like image 466
user3595338 Avatar asked May 18 '14 09:05

user3595338


2 Answers

If you do not want to have it bundled to the output folder additionally - you do not have to do anything. It is build into your exe, not need to check. Would always be true.


Okay, I understand because you dynamically build the name of your embedded resource you want to check it.

See here: WPF - check resource exists without structured exception handling

They basically check against Assembly.GetExecutingAssembly().GetManifestResourceNames()

You can use that as a starting point. But note that the resource name is not images/myimage.png but constructed from your namespace like YourApp.images.myimage.png. You might like to take a look at the contents of the built resourceNames array from that answer.

like image 75
ZoolWay Avatar answered Oct 24 '22 23:10

ZoolWay


Xamarin.Forms

From a working code, checks if auto-generated filename exists in embedded resources in the shared project (as described here https://developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Embedded_Images)

var assembly = typeof(App).GetTypeInfo().Assembly;
var AssemblyName = assembly.GetName().Name;
var generatedFilename = AssemblyName+".Images.flags.flag_" + item.CountryCode?.ToLower() + @".png";

bool found = false;
foreach (var res in assembly.GetManifestResourceNames())
{
    if (res == generatedFilename)
    {
        found = true;
        break;
    }
}

if (found) 
    UseGeneratedFilename();
else 
    UseSomeOtherPlaceholderImage;
like image 30
Nick Kovalsky Avatar answered Oct 25 '22 00:10

Nick Kovalsky