.NET : How to set user information in an EventLog Entry?

后端 未结 3 1871
孤独总比滥情好
孤独总比滥情好 2020-12-11 20:33

The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging...

System.Diagnostics.Ev         


        
3条回答
  •  鱼传尺愫
    2020-12-11 21:08

    Toughie ...

    I looked for a way to fill the user field with a .NET method. Unfortunately there is none, and you must import the plain old Win32 API [ReportEvent function](http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx) with a DLLImportAttribute

    You must also redeclare the function with the right types, as Platform Invoke Data Types says

    So

    BOOL ReportEvent(
    __in  HANDLE hEventLog,
    __in  WORD wType,
    __in  WORD wCategory,
    __in  DWORD dwEventID,
    __in  PSID lpUserSid,
    __in  WORD wNumStrings,
    __in  DWORD dwDataSize,
    __in  LPCTSTR *lpStrings,
    __in  LPVOID lpRawData
    );
    

    becomes

    [DllImport("Advapi32.dll", EntryPoint="ReportEventW",  SetLastError=true,
    CharSet=CharSet.Unicode)]
    bool WriteEvent(
      IntPtr hEventLog, //Where to find it ?
      ushort  wType,
      ushort  wCategory,
      ulong dwEventID,
      IntPtr lpUserSid, // We'll leave this struct alone, so just feed it a pointer
      ushort wNumStrings,
      ushort dwDataSize,
      string[] lpStrings,
      IntPtr lpRawData
    );
    

    You also want to look at [OpenEventLog](http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx) and [ConvertStringSidToSid](http://msdn.microsoft.com/en-us/library/aa376402(VS.85).aspx)

    Oh, and you're writing unmanaged code now... Watch out for memory leaks.Good luck :p

提交回复
热议问题