首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#_EventLog异常

C#_EventLog异常
EN

Stack Overflow用户
提问于 2018-08-09 16:10:02
回答 1查看 58关注 0票数 0

我正在尝试编写一个简单的事件日志,但遇到了“System.Security.SecurityException:未找到源...”我搜索了很多,但找不到一个有效的解决方案,如果有人能帮我,我真的很感激,我知道需要创建源代码,必须注册密钥,但密钥是什么,我应该如何做?

代码语言:javascript
复制
String source =“DemoTestApplication”;
String log = “DemoEventLog”;
EventLog demolog=new EventLog(log);
EventLog demolog=new EventLog(log);
demolog.Source=source;
demolog.writeEntry(“This is the first message to the log”,EventLogEntryType.Information);
EN

回答 1

Stack Overflow用户

发布于 2018-08-09 16:29:36

试试这个:

代码语言:javascript
复制
public static void LogEvent(string logBuffer, EventLogEntryType eventLogEntryType)
{
    const string source = "DemoTestApplication";

    // The user may not have permissions to access any event logs, therefore catch any SecurityExceptions.
    try
    {
        if (!EventLog.SourceExists(source))
        {
            // This requires administrator privileges.
            EventLog.CreateEventSource(source, "Application");
        }
        using (EventLog eventLog = new EventLog())
        {
            eventLog.Source = source;
            eventLog.WriteEntry(logBuffer, eventLogEntryType);
        }
    }
    catch (System.Security.SecurityException ex)
    {
        // Source was not found, but some or all of the event logs could not be searched.
        // May occur e.g., when trying to search Security event log.
        // EventLog.CreateEventSource requires permission to read all event logs to make sure 
        // that the new source name is unique.
        Debug.WriteLine(logBuffer);
        Debug.WriteLine(ex.ToString());
    }
}

通常,最好在以管理员/提升的权限运行时创建事件日志源,例如,在安装软件期间。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51761900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档