我在管理员帐户下运行此代码:
if (EventLog.Exists("AppName") == false)
EventLog.CreateEventSource("AppName", "Application"); // exception here
抛出SecurityException:
"找不到来源,但无法搜索部分或全部事件日志。要创建源,您需要具有读取所有事件日志的权限,以确保新源名称是唯一的。无法访问的日志:安全性。"
我可以在不执行此操作的情况下将事件写入EventLog,但它在日志中包含了这个看起来很糟糕的文本:
"找不到源应用程序中事件ID 0的描述。引发此事件的组件未安装在本地计算机上,或者安装已损坏。您可以在本地计算机上安装或修复组件。"
我错过了什么?
答案 0 :(得分:2)
我不知道这是否是处理问题的最佳方式,但它有效并且我找不到更好的解决方案:
// ---- Create Event Log Source ---------------------------------
//
// returns True if is it created or already exists.
//
// Only administrators can create event logs.
static public bool CreateEventLogSource()
{
System.Diagnostics.Debug.WriteLine("CreateEventLogSource....");
try
{
// this call is looking for this RegKey: HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\EventLog\Application\<app Name>
if (EventLog.SourceExists(Application.ProductName))
{
System.Diagnostics.Debug.WriteLine("Log exists, returning true.");
return true;
}
}
catch (System.Security.SecurityException)
{
// it could not find the EventLog Source and we are not admin so this is thrown
// when it tries to search the Security Log.
// We know it isn't there so ignore this exception
}
System.Diagnostics.Debug.WriteLine("EventLog Source doesn't exist....try to create it...");
if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
{
System.Diagnostics.Debug.WriteLine("Running as Admin....trying to create....");
try
{
EventLog.CreateEventSource(Application.ProductName, "Application");
System.Diagnostics.Debug.WriteLine("Successfully create EventLogSource");
return true;
}
catch (Exception Exp)
{
MessageBox.Show("Error Creating EventLog Source: " + Exp.Message, Application.ProductName);
return false;
}
}
else
{
System.Diagnostics.Debug.WriteLine("Need to restart with admin roles");
ProcessStartInfo AdminProcess = new ProcessStartInfo();
AdminProcess.UseShellExecute = true;
AdminProcess.WorkingDirectory = Environment.CurrentDirectory;
AdminProcess.FileName = Application.ExecutablePath;
AdminProcess.Verb = "runas";
try
{
Process.Start(AdminProcess);
return false;
}
catch
{
MessageBox.Show("The EventLog source was NOT created", Application.ProductName);
// The user refused to allow privileges elevation.
return false;
}
}
}
在这里打电话:
static void Main(string[] args)
{
if (CreateEventLogSource() == false)
return;