运行此代码获取此错误,任何人都可以帮助弄清楚这里发生了什么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace LSATest
{
class Program
{
public static List<string> listBox1 = new List<string>();
static void Main(string[] args)
{
DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate
UInt64 count;
IntPtr luidPtr = IntPtr.Zero;
LSAClass.LsaEnumerateLogonSessions(out count, out luidPtr); //gets an array of pointers to LUIDs
IntPtr iter = luidPtr; //set the pointer to the start of the array
for (ulong i = 0; i < count; i++) //for each pointer in the array
{
IntPtr sessionData;
LSAClass.LsaGetLogonSessionData(iter, out sessionData);
LSAClass.SECURITY_LOGON_SESSION_DATA data = (LSAClass.SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(LSAClass.SECURITY_LOGON_SESSION_DATA));
//if we have a valid logon
if (data.PSiD != IntPtr.Zero)
{
//get the security identifier for further use
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD);
//extract some useful information from the session data struct
string username = Marshal.PtrToStringUni(data.Username.buffer).Trim(); //get the account username
string domain = Marshal.PtrToStringUni(data.LoginDomain.buffer).Trim(); //domain for this account
string authpackage = Marshal.PtrToStringUni(data.AuthenticationPackage.buffer).Trim(); //authentication package
LSAClass.SECURITY_LOGON_TYPE secType = (LSAClass.SECURITY_LOGON_TYPE)data.LogonType;
DateTime time = systime.AddTicks((long)data.LoginTime); //get the datetime the session was logged in
//do something with the extracted data, ie, add to a display control....
listBox1.Add("User: " + username + " *** Domain: " + domain + " *** Login Type: (" + data.LogonType + ") " + secType.ToString() + " *** Login Time: " + time.ToLocalTime().ToString());
}
iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(LSAClass.LUID))); //move the pointer forward
LSAClass.LsaFreeReturnBuffer(sessionData); //free the SECURITY_LOGON_SESSION_DATA memory in the struct
}
LSAClass.LsaFreeReturnBuffer(luidPtr); //free the array of LUIDs
}
}
}
答案 0 :(得分:1)
错误是因为sessionData
是null
。那是因为LsaGetLogonSessionData
失败了。要进一步诊断,您需要开始关注API函数的返回值,并在发生故障时检查错误代码。那是你的下一步。
顺便说一句,您已经错误地声明了count
变量。在C头文件中,它被声明为ULONG
。这是一个无符号的32位整数,使其在C#中成为uint
。我没有检查过这个。