Why does EventRecord.FormatDescription() return null?

后端 未结 2 1360
[愿得一人]
[愿得一人] 2021-02-08 12:29

When using System.Diagnostics.Eventing.Reader.EventLogQuery to read events from the Windows Event Log, the EventRecord.FormatDescription() method somet

2条回答
  •  你的背包
    2021-02-08 12:49

    This is due to a bug in the .NET framework.

    Basically what you need to do to work around this bug is to set the CurrentCulture to "en-US".

    Example:

    var beforeCulture = Thread.CurrentThread.CurrentCulture;
    
    try
    {
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    
      using (var session = new EventLogSession(ipOrAddress, userDomain, username, password, SessionAuthentication.Default))
      {
        var query = new EventLogQuery("System", PathType.LogName, queryString)
          {
            ReverseDirection = true,
            Session = session
          };
    
        using (var reader = new EventLogReader(query))
        {
          for (var record = reader.ReadEvent(); record != null; record = reader.ReadEvent())
          {
            // Read event records
            string message = record.FormatDescription();
          }
        }
      }
    }
    finally
    {
      Thread.CurrentThread.CurrentCulture = beforeCulture;
    }
    

    This workaround is was very hard to find, so I thought I would document it a place where it will be indexed by Google. I found it in an old MS Connect case, but it has been closed with a status of "wont fix".

    UPDATE: The bug has been reported for .NET 4 as well and the status is "Sent to Engineering Team for consideration" and comment alluding that the bug might be fixed in the next major .NET framework release (v5).

提交回复
热议问题