2012-07-02 37 views
1

我想在我的代碼中使用http://msdn.microsoft.com/en-us/library/aa370654%28VS.85%29.aspx。但出於某種原因,我無法找到使用它的命名空間。三我認爲會工作是我可以在C#中使用NetUserGetInfo嗎?

using System.DirectoryServices.AccountManagement; 
using System.Runtime.InteropServices; 
using System.DirectoryServices; 

但這些都沒有工作。所有使用NetUserGetInfo的例子都可以在C++中找到,而不是C#。這讓我想,也許我不能在C#中使用它。我可以嗎?如果是這樣,我應該使用什麼命名空間來訪問NetUserGetInfo函數?任何幫助表示讚賞。

回答

3

你在找什麼名字空間?命名空間是.NET特定的概念。 NetUserGetInfo是一個Win32非託管功能。如果你想從託管的.NET代碼調用它,你需要編寫一個託管包裝並通過P/Invoke來調用它。

下面是在此情況下,其示出了下面的託管包裝一個useful site

[DllImport("Netapi32.dll", CharSet=CharSet.Unicode, ExactSpelling=true)] 
private extern static int NetUserGetInfo(
    [MarshalAs(UnmanagedType.LPWStr)] string ServerName, 
    [MarshalAs(UnmanagedType.LPWStr)] string UserName, 
    int level, 
    out IntPtr BufPtr 
); 

用戶定義的結構:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 
public struct USER_INFO_10 
{ 
    [MarshalAs(UnmanagedType.LPWStr)] 
    public string usri10_name; 
    [MarshalAs(UnmanagedType.LPWStr)] 
    public string usri10_comment; 
    [MarshalAs(UnmanagedType.LPWStr)] 
    public string usri10_usr_comment; 
    [MarshalAs(UnmanagedType.LPWStr)] 
    public string usri10_full_name; 
} 

和樣品調用:

public bool AccountGetFullName(string MachineName, string AccountName, ref string FullName) 
{ 
    if (MachineName.Length == 0) 
    { 
     throw new ArgumentException("Machine Name is required"); 
    } 
    if (AccountName.Length == 0) 
    { 
     throw new ArgumentException("Account Name is required"); 
    } 
    try 
    { 
     // Create an new instance of the USER_INFO_1 struct 
     USER_INFO_10 objUserInfo10 = new USER_INFO_10(); 
     IntPtr bufPtr; // because it's an OUT, we don't need to Alloc 
     int lngReturn = NetUserGetInfo(MachineName, AccountName, 10, out bufPtr) ; 
     if (lngReturn == 0) 
     { 
      objUserInfo10 = (USER_INFO_10) Marshal.PtrToStructure(bufPtr, typeof(USER_INFO_10)); 
      FullName = objUserInfo10.usri10_full_name; 
     } 
     NetApiBufferFree(bufPtr); 
     bufPtr = IntPtr.Zero; 
     if (lngReturn == 0) 
     { 
      return true; 
     } 
     else 
     { 
      //throw new System.ApplicationException("Could not get user's Full Name."); 
      return false; 
     } 
    } 
    catch (Exception exp) 
    { 
     Debug.WriteLine("AccountGetFullName: " + exp.Message); 
     return false; 
    } 
} 
2

NetUserGetInfo是一個需要P /調用的Win32 API。使用.NET時,最好使用.NET diectory services API。 UserPrincipal班可能是一個很好的起點。

相關問題