gpt4 book ai didi

c# 写入事件查看器

转载 作者:IT王子 更新时间:2023-10-29 03:47:51 26 4
gpt4 key购买 nike

我试图在我的 C# 代码中写入事件查看器,但我收到了美妙的消息“对象引用未设置为对象的实例”。我很感激这段代码的一些帮助,无论是它有什么问题,甚至是更好的方法。这是我要写入事件日志的内容:

private void WriteToEventLog(string message)
{
string cs = "QualityDocHandler";
EventLog elog = new EventLog();
if (!EventLog.SourceExists(cs))
{
EventLog.CreateEventSource(cs, cs);
}
elog.Source = cs;
elog.EnableRaisingEvents = true;
elog.WriteEntry(message);
}

这里是我尝试调用它的地方:

private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
try
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
catch (Exception e)
{
WriteToEventLog(e.ToString());
return null;
}
}

最佳答案

问题可能是您试图在不存在的日志中创建事件源。您需要指定“应用程序”日志。

尝试将其更改为:

if (!EventLog.SourceExists(cs))
EventLog.CreateEventSource(cs, "Application");

EventLog.WriteEntry(cs, message, EventLogEntryType.Error);

此外:在 sharepoint 内部,如果应用程序以登录用户身份运行(通过 Windows 身份验证或委托(delegate)),则用户将无权创建事件源。如果是这种情况,一种技巧是使用 ThreadPool 线程创建事件,该线程在创建时将具有运行 App Pool 的用户的安全上下文。

关于c# 写入事件查看器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1133355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com