How can I validate Event Log Writing Permissions without using an try catch? I've read the following question: Checking Event Log writing Permissions without writing an entry , but the Answer suggests using the EventLogPermissionAttribute
. As far as I know I can't use this to validate permission, it just throws an Exception
when it doesn't have the requested permission.
My code now looks something like this:
public void WriteMessage(string message)
{
try {
var trace = new TraceSource("MySource");
trace.TraceEvent(TraceEventType.Information, 1000, message);
} catch() {
var log = LogManager.GetLogger<MyClass>();
log.Info(message);
}
}
But I would like something like this:
public void WriteMessage(string message)
{
if(EventLogPermission("MySource"))
{
var trace = new TraceSource("MySource");
trace.TraceEvent(TraceEventType.Information, 1000, message);
} else {
var log = LogManager.GetLogger<MyClass>();
log.Info(message);
}
}
Ofcourse at the end it doesn't make much difference but using a try catch for logic just feels dirty.
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int RegOpenKeyEx(
UIntPtr hKey,
string subKey,
int ulOptions,
int samDesired,
out UIntPtr hkResult);
public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(0x80000002u);
public static int KEY_WRITE = 0x20006;
/// <summary>
/// This method checks write permissions to HKLM\SYSTEM\CurrentControlSet\Services\EventLog which is necessary to create event log source
/// </summary>
/// <returns>True if permission to create Event log source is granted, false if not</returns>
public bool HasCurrentUserEventLogWritePermissions()
{
UIntPtr x;
long err = RegOpenKeyEx(HKEY_LOCAL_MACHINE, @"SYSTEM\CurrentControlSet\Services\EventLog", 0, KEY_WRITE, out x);
return err == 0;
}
OK. I Give up and this just to tell you the failed attempts. I searched a little, reflected a little more and the answer is disappointing: you can't do this the way you like.
I tried to find a way for checking EventLogPermission
(Security permissions in general) without getting exception: FAILED.
Tried opening the RegKey without getting an exception: FAILED.
There are in fact unmanaged APIs out there that may be useful, but I think if your application lacks even EventLogPermission
who would give it SecurityUnmngdCodeAccess
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.