我有一本字典,我必须在用户登录时添加一个对象,并且需要在用户在 Windows 中注销时删除该对象。我还将字典序列化为 xml。由于我是 C# 以及 windows 服务的新手,我有一些疑问。
这是我的代码。
public class UserSessionCapturePlugin : IInformServiceHandler
{
public Dictionary<int, UserSessionInfo> UserSessionLookupTable = new Dictionary<int, UserSessionInfo>();
public void OnSessionChange(SessionChangeDescription changeDescription)
{
switch (changeDescription.Reason)
{
//Case of Logon
case SessionChangeReason.SessionLogon:
//CreateRunningProcessesLog("UserSession-SessionLogon");
UserSession userSessionLogin = new UserSession()
{
UserName = MachineHelper.GetUsername(),
UserGuid = MachineHelper.GetUserGuid(),
MachineGuid = MachineHelper.GetMachineGUID(),
LoginTime = DateTime.Now.ToUniversalTime(),
SessionGuid = Guid.NewGuid(), //New Guid generated for tracking the UserSession, this will be created on on logon
IsReadable = false,
SessionId = changeDescription.SessionId,
};
UserSessionInfo userSessionInfoLogin = new UserSessionInfo()
{
UserName = MachineHelper.GetUsername(),
SessionGuid = userSessionLogin.SessionGuid,
IsActiveUser = true,
SessionId = changeDescription.SessionId,
LoginTime = userSessionLogin.LoginTime,
State = RowState.Added,
};
UserSessionLookupTable.Add(userSessionInfoLogin.SessionId, userSessionInfoLogin);
XmlSerializer serializer = new XmlSerializer(typeof(Dictionary<Guid, UserSessionInfo>));
TextWriter textWriter = new StreamWriter(@"UserSessionLookupDictionarySerialized.xml");
serializer.Serialize(textWriter, UserSessionLookupTable);
textWriter.Close();
//Case of Logoff
case SessionChangeReason.SessionLogoff:
UserSession userSessionLogoff = new UserSession()
{
UserName = MachineHelper.GetUsername(),
UserGuid = MachineHelper.GetUserGuid(),
MachineGuid = MachineHelper.GetMachineGUID(),
LogOffTime = DateTime.Now.ToUniversalTime(),
IsReadable = true,
SessionId = changeDescription.SessionId,
};
UserSessionLookupTable.Remove(userSessionLogoff.SessionId);
XmlSerializer serializer = new XmlSerializer(typeof(Dictionary<Guid, UserSessionInfo>));
TextWriter textWriter = new StreamWriter(@"UserSessionLookupDictionarySerialized.xml");
serializer.Serialize(textWriter, UserSessionLookupTable);
textWriter.Close();
break;
}
}
}
但我有以下疑问
如果有多个用户登录,这个 xml 会被替换为最后登录用户的详细信息,还是会添加新用户的附加条目?
在注销时,用户详细信息是否也会从 xml 中删除,或者是否需要任何其他方法(如反序列化和删除条目)?
我目前无法调试或运行代码,这就是我在这里发布它的原因。