运行这个代码得到这个错误,有没有人能帮我弄清楚这是怎么回事?

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
}
}}
发布于 2012-03-22 20:29:05
错误是因为sessionData为null。这是因为LsaGetLogonSessionData正在失败。为了进一步诊断这个问题,您需要开始关注API函数的返回值,并在失败的情况下检查错误代码。这就是你的下一步。
顺便说一句,您错误地声明了count变量。在C头文件中,它被声明为ULONG。这是一个无符号的32位整数,在C#中是uint。我没有检查过比这更多的东西了。
https://stackoverflow.com/questions/9822241
复制相似问题