我正在尝试在我的 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;
}
}