本文介绍了从C#托管代码调用win32 CreateProfile()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速提问(希望如此),如何正确地从C#(托管代码)中调用win32函数CreateProfile()?我试图自己设计一个解决方案,但无济于事.

Quick question (hopefully), how do I properly call the win32 function CreateProfile() from C# (managed code)? I have tried to devise a solution on my own with no avail.

CreateProfile()的语法为:


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

可以在 MSDN中找到支持文档库.

我到目前为止的代码发布在下面.

The code I have so far is posted below.

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 .任何有关此事的有用信息都将受到欢迎.


The problem is that no user profile is ever created and CreateProfile() returns an error code of: 0x800706f7. Any helpful information on this matter is more than welcomed.

谢谢,
-西恩(Sean)

Thanks,
-Sean


更新:解决了!pszProfilePath的字符串缓冲区的长度不能大于260.


Update:Solved!string buffer for pszProfilePath cannot have a length greater than 260.

推荐答案

对于out参数,应设置编组.更重要的是,通过传递StringBuilder,您已经隐式具有输出参数.因此,它应该变为:

For the out parameter you should set the marshalling. More importantly, by passing a StringBuilder you already implicitly have an output parameter. Thus, it should become:

[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);

这篇关于从C#托管代码调用win32 CreateProfile()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 11:22