2011-04-28 124 views
3

快速問題(希望),如何從C#(託管代碼)正確調用win32函數CreateProfile()?我試圖自己設計一個解決方案,但沒有成功。從C#託管代碼調用win32 CreateProfile()管理代碼

爲CreateProfile()的語法是:


HRESULT WINAPI CreateProfile(
    __in LPCWSTR pszUserSid, 
    __in LPCWSTR pszUserName, 
    __out LPWSTR pszProfilePath, 
    __in DWORD cchProfilePath 
);

的證明文件可在MSDN library找到。

我到目前爲止的代碼發佈在下面。

DLL導入:


[DllImport("userenv.dll", CharSet = CharSet.Auto, SetLastError = true)] 
private static extern int CreateProfile(
         [MarshalAs(UnmanagedType.LPWStr)] string pszUserSid, 
         [MarshalAs(UnmanagedType.LPWStr)] string pszUserName, 
         [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, 
         uint cchProfilePath); 

調用函數:


/* Assume that a user has been created using: net user TestUser password /ADD */ 

// Get the SID for the user TestUser 
NTAccount acct = new NTAccount("TestUser"); 
SecurityIdentifier si = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); 
String sidString = si.ToString(); 

// Create string buffer 
StringBuilder pathBuf = new StringBuilder(260); 
uint pathLen = (uint)pathBuf.Capacity; 

// Invoke function 
int result = CreateProfile(sidString, "TestUser", pathBuf, pathLen); 


的問題是,沒有用戶配置文件是曾經創造和CreateProfile()返回錯誤代碼:0x800706f7。任何關於此事的有用信息都不會受到歡迎。

感謝,
-Sean


更新: 解決了!對於pszProfilePath 字符串緩衝區不能有長度大於260

+0

錯誤codfe 0x800706f7的含義:存根收到壞數據。不知道這是否有幫助。 – PVitt 2011-04-28 12:26:23

+0

@PVitt,這是很好的知道,但我不知道我輸入錯誤。 – Sean 2011-04-28 12:29:08

+0

您不需要任何MarshalAs屬性,因爲您只是重複默認設置。 – 2011-04-28 14:28:37

回答

3

對於out參數,您應該設置編組。更重要的是,通過傳遞一個StringBuilder,你已經隱含了一個輸出參數。因此,它應該成爲:

[DllImport("userenv.dll", CharSet = CharSet.Auto)] 
private static extern int CreateProfile(
        [MarshalAs(UnmanagedType.LPWStr)] string pszUserSid, 
        [MarshalAs(UnmanagedType.LPWStr)] string pszUserName, 
        [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, 
        uint cchProfilePath); 

調用此方法:

int MAX_PATH = 260; 
StringBuilder pathBuf = new StringBuilder(MAX_PATH); 
uint pathLen = (uint)pathBuf.Capacity; 

int result = CreateProfile(sidString, "TestUser", pathBuf, pathLen); 
+0

應將pszUserSid和pszUserName編組爲LPWStr嗎?它們被定義爲LPCWSTR,其中pszProfilePath被定義爲LPWSTR .. – Sean 2011-04-28 13:05:36

+0

是的。 LPCWSTR是一個const LPWSTR,即被調用者(CreateProfile)不會修改傳入的字符串。 – 2011-04-28 13:09:04

+0

好吧,我會編組我的[Out]參數,看它是否有效。 – Sean 2011-04-28 13:13:19

1

它可能不是唯一的問題更大,但你需要的[Out]屬性添加到pszProfilePath參數在DLL進口報關。

+0

我添加了[Out]屬性,但它仍然無效。我迷失在接下來的嘗試。 – Sean 2011-04-28 12:18:09