CreateEventSource即使在Admin帐户下也会产生异常



我在管理员帐户下运行此代码:

if (EventLog.Exists("AppName") == false)
    EventLog.CreateEventSource("AppName", "Application");  // exception here

抛出SecurityException:

"未找到源,但无法搜索部分或全部事件日志。要创建源,您需要读取所有事件日志的权限,以确保新源名称是唯一的。不可访问的日志:安全。"

我可以写事件到EventLog没有这样做,但它包括这个蹩脚的文本在日志中:

"无法找到源应用程序的事件ID 0的描述。引发此事件的组件未安装在本地计算机上,或者安装已损坏。您可以在本地计算机上安装或修复该组件。"

我错过了什么?

我不知道这是否是处理问题的最佳方法,但它有效,我找不到更好的解决方案:

// ---- 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_MACHINESYSTEMControlSet001ServicesEventLogApplication<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;

相关内容

最新更新