Reputation: 925
In a Xamarin Forms (3.0) application, what method(s) would I use to tell if a drawable resource exists in my Android project from shared project code?
In iOS, I can use NSFileManager to see if the file exists in my iOS project's "Resources" folder:
#if __IOS__
private bool DoesImageExist(string image)
{
//WORKS
return Foundation.NSFileManager.DefaultManager.FileExists(image);
}
#endif
In Android, I thought it should be part of the Assembly Resources, but that just returns my App.xaml file.
#if __ANDROID__
private bool DoesImageExist(string image)
{
//DOES NOT WORK
if(MyApp.Current?.GetType() is Type type)
foreach (var res in Assembly.GetAssembly(type).GetManifestResourceNames())
{
if (res.Equals(image, StringComparison.CurrentCultureIgnoreCase))
return true;
}
return false;
}
#endif
Upvotes: 0
Views: 706
Reputation: 8090
How to specifically check if a drawable exists by name in android would work like something this:
#if __ANDROID__
public bool DoesImageExist(string image)
{
var context = Android.App.Application.Context;
var resources = context.Resources;
var name = Path.GetFileNameWithoutExtension(image);
int resourceId = resources.GetIdentifier(name, "drawable", context.PackageName);
return resourceId != 0;
}
#endif
If your code is in a pcl or .net standard assembly, you will have to create an abstraction. Some kind of Ioc library works well for this. You can also have Android or iOS implement the abstract interface and make that available as a singleton somewhere. It's not as elegant, but it would work.
Basically you would implement something like this:
public interface IDrawableManager
{
bool DoesImageExist(string path);
}
Then have two implementations:
public class DroidDrawableManager : IDrawableManager
{
var context = Android.App.Application.Context;
var resources = context.Resources;
var name = Path.GetFileNameWithoutExtension(image);
int resourceId = resources.GetIdentifier(name, "drawable", context.PackageName);
return resourceId != 0;
}
public class IOSDrawableManager : IDrawableManager
{
public bool DoesImageExist(string image)
{
return Foundation.NSFileManager.DefaultManager.FileExists(image);
}
}
I've uploaded a working sample to github:
https://github.com/curtisshipley/ResourceExists
Upvotes: 1