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.
The syntax for CreateProfile() is:
HRESULT WINAPI CreateProfile(
  __in   LPCWSTR pszUserSid,
  __in   LPCWSTR pszUserName,
  __out  LPWSTR pszProfilePath,
  __in   DWORD cchProfilePath
);The supporting documents can be found in the MSDN library.
The code I have so far is posted below.
DLL Import:
[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);
Invoking the function:
/* 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);
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.
Thanks,
-Sean
Update:
Solved!
string buffer for pszProfilePath cannot have a length greater than 260.
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);
Calling this method:
int MAX_PATH = 260;
StringBuilder pathBuf = new StringBuilder(MAX_PATH);
uint pathLen = (uint)pathBuf.Capacity;
int result = CreateProfile(sidString, "TestUser", pathBuf, pathLen);
It may not be the only problem but you need to add the [Out] attribute to the pszProfilePath parameter in your DLL import declaration.
User contributions licensed under CC BY-SA 3.0