c#读取远程服务器的事件日志

时间:2012-07-19 17:24:47

标签: c# permissions event-log

我正在关注this帖子并试图运行代码(下面复制),而且我的问题略有不同。我可以远程连接到服务器并通过事件查看器程序查看事件日志,但我无法遍历代码中的事件。我收到一个InvalidOperationException,说“无法在机器上打开日志EventLogName .Windows没有提供错误代码。” System.ComponentModel.Win32Exception类型的内部异常也显示“访问被拒绝。”

private static bool GetEventLogData(DateTime start)
{
    var log = new EventLog("EventLogName", "SERVER.domain.net");
    bool errorFound = false;
    foreach (EventLogEntry entry in log.Entries)
    {
        if ((entry.EntryType == EventLogEntryType.Error) && 
            (entry.TimeGenerated >= start))
        {
            Console.WriteLine("Error in Event Log:\n" + entry.Message + "\n");
            errorFound = true;
        }
    }
    return errorFound;
}

有什么想法吗?

修改

异常数据如下。我无法发布服务器名称,因为它是公司信息。我在尝试读取事件日志时收到错误。我绝对相信我可以读取日志,因为我可以远程连接我的帐户并使用事件查看器读取日志。

System.InvalidOperationException was unhandled
  Message=Cannot open log EventLogName on machine SERVER.domain.net. Windows has not provided an error code.
  Source=System
  StackTrace:
       at System.Diagnostics.EventLogInternal.OpenForRead(String currentMachineName)
       at System.Diagnostics.EventLogInternal.GetEntryAtNoThrow(Int32 index)
       at System.Diagnostics.EventLogEntryCollection.EntriesEnumerator.MoveNext()
       at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
       at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
       at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
       at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
       at MyApp.Program.GetEventLogData(String machineName, DateTime start) in c:\users\me\documents\visual studio 2010\Projects\MyApp\MyApp\Program.cs:line 45
       at MyApp.Program.Main(String[] args) in c:\users\me\documents\visual studio 2010\Projects\MyApp\MyApp\Program.cs:line 28
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.ComponentModel.Win32Exception
       Message=Access is denied
       ErrorCode=-2147467259
       NativeErrorCode=5
       InnerException: 

1 个答案:

答案 0 :(得分:1)

这很可能是政策许可问题。请参阅TechNet上的Giving Non Administrators permission to read Event Logs Windows 2003 and Windows 2008博客条目。一旦我这样做,我就能让你的代码工作。对于Windows 2008 Server及更高版本,只需将用户添加到事件日志读取器本地安全组即可。直到我这样做,我才得到同样的错误。