heights1976
heights1976

Reputation: 500

Xamarin Cross Platform Application Package Name in C#

Is there a way to programmatically access the application package name/namespace/version information in Xamarin portable C# code?

Like this (link is how to access for Android, I want to know if there is a pre-existing C# cross platform way to access this in the portable class code.)

Not this.

Upvotes: 4

Views: 9098

Answers (1)

tkrz
tkrz

Reputation: 250

i got answer to your problem, but it is using dependency service to work. There is no other way if there is no Xamarin plugin. Here is the code:

Interface in pcl project:

public interface IPackageName
{
    string PackageName { get; }
}

Android implementation:

public class PackageNameDroid : IPackageName
{
    public PackageNameDroid()
    {
    }

    public string PackageName
    {
        get { return Application.Context.PackageName; }
    }
}

iOS implementation:

public class PackageNameIOS : IPackageName
{

    public PackageNameIOS()
    {
    }

    public string PackageName
    {
        get { return NSBundle.MainBundle.BundleIdentifier; }
    }

}

Don't forget to mark platform files for dependency service in Android file:

[assembly: Xamarin.Forms.Dependency(typeof(PackageNameDroid))]

and iOS file:

[assembly: Xamarin.Forms.Dependency(typeof(PackageNameIOS))]

Now you're good to go and can use it in PCLs just like that:

string packageName = DependencyService.Get<IPackageName>().PackageName;

Hope it helps others.

Upvotes: 19

Related Questions