2012-03-22 78 views
0

Runnnig此代碼得到此錯誤,有沒有人可以幫助找出這裏發生了什麼?.NET C/C++ P/INVOKE異常

enter image description here

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

這不是C和C++。這是C#。 – 2012-03-22 12:39:39

回答

1

這個錯誤是因爲sessionDatanull。這是因爲LsaGetLogonSessionData失敗。爲了進一步診斷,您需要開始關注API函數的返回值,並在發生故障時檢查錯誤代碼。這是你的下一步。

另外,您已經聲明count變量不正確。在C頭文件中,它被聲明爲ULONG。這是一個無符號的32位整數,它使得C#中的uint成爲可能。我沒有檢查過任何東西。