我使用 EventLogWatcher 来跟踪日志中的事件。程序停止/启动后,我需要保存/恢复书签事件。事件的书签由 EventBookmark 类https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.eventbookmark?view=netframework-4.8表示,并且继承自ISerializable接口。但是我不能序列化该类的对象。因为它没有默认的ctor,所以ctor没有参数。 我对 C#不太熟悉,因为我一周使用一次。您能帮我理解为什么无法从该类的对象序列化为什么该类从ISerializable接口继承吗?对于我来说,这很奇怪,因为我听不懂什么,但我想知道。 此外建设者 EventBookmark(SerializationInfo,StreamingContext)和 GetObjectData(SerializationInfo,StreamingContext)受保护。
那么,如何序列化和反序列化 EventBookmark 类的对象?
已更新(工作代码),谢谢jdweng的帮助
namespace ConsoleApp
{
using System;
public class Program
{
static void Main(string[] args)
{
string logName = "Application";
string filter = "*";
System.Diagnostics.Eventing.Reader.EventLogQuery eventQuery = new System.Diagnostics.Eventing.Reader.EventLogQuery(
logName,
System.Diagnostics.Eventing.Reader.PathType.LogName,
filter
);
System.Diagnostics.Eventing.Reader.EventLogReader eventLogReader = new System.Diagnostics.Eventing.Reader.EventLogReader(eventQuery);
System.Diagnostics.Eventing.Reader.EventRecord eventRecord = eventLogReader.ReadEvent();
System.Diagnostics.Eventing.Reader.EventBookmark eventBookmark = eventRecord.Bookmark;
if (eventBookmark != null)
{
System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.Stream stream = new System.IO.MemoryStream();
formatter.Serialize(stream, eventBookmark);
stream.Position = 0;
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string result = reader.ReadToEnd();
Console.WriteLine("event bookmark: {0}", result);
stream.Position = 0;
System.Diagnostics.Eventing.Reader.EventBookmark newEventBookmark = (System.Diagnostics.Eventing.Reader.EventBookmark)formatter.Deserialize(stream);
if (newEventBookmark != null/* && eventBookmark.Equals(newEventBookmark)*/)
{
Console.WriteLine("Deserialization successfully passed");
}
else
{
Console.WriteLine("Deserialization failed");
}
}
else
{
Console.WriteLine("cannot read event bookmark");
}
Console.ReadKey();
}
}
}