For Extended Events, the Microsoft.SqlServer.XEvent.XELite package available on NuGet facilitates reading XE traces programmatically. The NuGet page has C# examples.
Another method is with Microsoft.SqlServer.XEvent.Linq.QueryableXEventData. The Micrrosoft.SqlServer.XE.Core.dll and Micrrosoft.SqlServer.Xevent.Linq.dll assemblies are located in the SQL installation shared directory (e.g. C:\Program Files\Microsoft SQL Server\160\Shared). The fields and actions captured by the XE trace are exposed in separate collections. Below is a C# snippet to extract XML deadlock reports from the system_health
trace:
using (var xeEvents = new Microsoft.SqlServer.XEvent.Linq.QueryableXEventData(@"C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Log\system_health_*.xel"))
{
foreach (var xeEvent in xeEvents)
{
if (xeEvent.Name == "xml_deadlock_report")
{
Console.WriteLine($"{xeEvent.Name}: {xeEvent.Fields["xml_report"].Value}");
}
}
}