24

I need to display the app's build version in my settings page.

So how can i get the versionCode and versionName from AndroidManifest.xml file programmatically.

Or

Is there any way to get the build version programmatically in xamarin.forms.

Tushar patel
  • 3,279
  • 3
  • 27
  • 30

4 Answers4

32

With a Dependency service:

For iOS:

using Foundation;

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

namespace XXX.iOS
{
    public class Screen_iOS : IScreen
    {

        public string Version
        {
            get
            {
                NSObject ver = NSBundle.MainBundle.InfoDictionary["CFBundleShortVersionString"];
                return ver.ToString();
            }
        }

    }
}

For Android:

using Xamarin.Forms;

[assembly: Dependency(typeof(ScreenAndroid))]

namespace XXX.Droid
{
    class ScreenAndroid : Java.Lang.Object, IScreen
    {

        public string Version
        {
            get
            {
                var context = Forms.Context;
                return context.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
            }
        }

    }
}

And the interface:

interface IScreen
{
    string Version { get; }
}
Paddy
  • 79
  • 1
  • 3
  • 13
Mario Galván
  • 3,964
  • 6
  • 29
  • 39
  • Note that it only worked for me when I used the full namespace in the registration attribute, which would be in this case : assembly: Dependency(typeof(XXX.Droid.ScreenAndroid ))] – bergmeister Sep 10 '17 at 09:45
  • 2
    Forms.Context is obsolete. Use Android.App.Application.Context instead. https://stackoverflow.com/questions/47353986/xamarin-forms-forms-context-is-obsolete – James Esh Jul 23 '18 at 21:03
32

For version name:

Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionName

For version code:

Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0).VersionCode
Fabian
  • 13,603
  • 6
  • 31
  • 53
Parth Patel
  • 3,937
  • 2
  • 27
  • 44
19

In Xamarin.Essentials you can use the following:

Version version = AppInfo.Version;

From there you can get the build version.

If you really just want the build number you can also use the shortcut:

string buildNumber = AppInfo.BuildString;
Gabriel Weidmann
  • 756
  • 12
  • 16
1

In Xamarin.Android you could always try:

public double GetAppVersion()
{
   var info = AppContext.PackageManager.GetPackageInfo(AppContext.PackageName, 0);
   return info.VersionCode;
}

and then you will need to use dependency injection to call this method from your Xamarin.Forms project.

JKennedy
  • 18,150
  • 17
  • 114
  • 198