tags:

views:

1072

answers:

4

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.EventLog.WriteEntry("MyEventSource", "My Special Message")

Is there a way to set the user information in the resulting event log entry using .NET?

A: 

You need to add it yourself into the event message.

Use the System.Security.Principal namespace to get the current identity of the thread logging the event.

Kev
A: 

Usually, the user executing the code that calls the EventLog.WriteEntry method will be the user displayed in the event log for the entry.

You could try impersonating another user by creating your own Principal and Identity and associating it with the current thread, however this is not advised as it could introduce security issues and will definitely complicate your application.

Ash
A: 

Including the user in the message is an obvious way around it. But I actually want to set the User field of the event log entry.

Ash...

"the user executing the code that calls the EventLog.WriteEntry method will be the user displayed in the event log for the entry"

This is not correct in my experience. The user field is not populated by the EventLog.WriteEntry call.

Anybody else got a way to do this?

Kevin Read
+3  A: 

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 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 and ConvertStringSidToSid

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

Johan Buret