Wednesday, April 6, 2022

How to calculate Age based on a birthday in C#

Here is a sample code to calculate Age based on a birthday in C#.
using System;
public class HelloWorld
{
    public static void Main(string[] args)
    {
        DateTime birthdate = DateTime.ParseExact("1989-02-25", "yyyy-MM-dd",                                               System.Globalization.CultureInfo.InvariantCulture);
        var today = DateTime.Today;
        
        var age = today.Year - birthdate.Year;
        
        today.AddYears(-age);
        
        Console.WriteLine (age);
    }
}

How to get the path of the assembly of your code is in

Here is a sample code to get the path of the assembly of your code is in.
    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
    var assemblyPath = Path.GetDirectoryName(path);

How to get the assembly file version in C#

Here is a sample code to get assembly file version in C#.
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fvi.FileVersion;

Another approach is,
var version = Application.ProductVersion;
This approach requires reference to below namespace.
System.Windows.Forms