4

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.

Community
  • 1
  • 1
heights1976
  • 480
  • 6
  • 16
  • There is no method in Xamarin.Forms but if you want you can create a dependency service to get the package name from respective platforms. – Akash Amin May 22 '16 at 10:05
  • Oh well. I was hoping to avoid that. I'll post the solution here when done (for iOS and Android). – heights1976 May 22 '16 at 16:35

1 Answers1

19

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.

tkrz
  • 240
  • 3
  • 10