首页 > 解决方案 > The description string for parameter reference (%1) could not be found

问题描述

I'm getting this exception when trying to read from the Windows Log using C#'s method EventRecord.FormatDescription():

System.Diagnostics.Eventing.Reader.EventLogException: The description string for parameter reference (%1) could not be found
   at System.Diagnostics.Eventing.Reader.EventLogException.Throw(Int32 errorCode)
   at System.Diagnostics.Eventing.Reader.NativeWrapper.EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, EvtFormatMessageFlags flag)
   at System.Diagnostics.Eventing.Reader.ProviderMetadataCachedInformation.GetFormatDescription(String ProviderName, EventLogHandle eventHandle)

The exception happens when the text of the event contains the string %% followed by a long number (some events from a source I don't control contain that pattern). Those %% are intended to be just text, I don't expect any parsing intelligence from Windows at that point.

Do you know what I can do to avoid .Net from throwing this error when the text of an event contains that pattern?

Here are the PowerShell commands that will cause the exception next time you try to read the event from a C# program:

New-EventLog -LogName Application -Source MyApp
Write-EventLog -Source MyApp -LogName Application -Message "%%4294967295" -EventId 3

标签: c#.netwindowsevent-log

解决方案


我最终实施的解决方法如下:

    private string FormatEventDescription(EventRecord eventRecord)
    {
        try
        {
            return eventRecord.FormatDescription();
        }
        catch (EventLogException e)
        {
            return eventRecord.ToXml();
        }
    }

这不太令人满意,因为 XML 不是用户友好的,但至少它具有我们需要了解 EventRecord 的原始内容所需的所有信息。请注意,XML 内部不一定包含描述字符串,有时这些事件有一个参数列表,用于填充消息模板以生成描述字符串,因此在这种情况下,您将获得原始参数。


推荐阅读