Setting the Home Drive with %UserName% programmatically with DirectoryEntry in c# .Net

233 views Asked by At

I have a software automating some usercreation.

At some point, the home drive is set with the following code:
UserAccountCreation.cs

createdUser.HomeDirectory = @"\\domain.local\Data\Home\%UserName%";

User.cs

/// <summary>
/// <para>path</para>
/// <para>this network path will be mapped as the home drive to the user</para>
/// eg. "\\server\Data\Home\mustema1"
/// </summary>
public string HomeDirectory
{
    get
    {
        _HomeDirectory ??= GetProperty("path");// if null, pull value;
        return _HomeDirectory;
    }
    set
    {
        if (value != _HomeDirectory)
        {
            _HomeDirectory = value;
            //SetProperty("path", _HomeDirectory);
            SetProperty("HomeDirectory", _HomeDirectory);
            SetProperty("HomeDrive", "H");
        }
    }
}
/// <summary>
/// this function calls the corresponsing active directory function in order to populate a poperty of the given user
/// </summary>
/// <param name="property">which property to poulate</param>
/// <param name="value">what value should the property have?</param>
private void SetProperty(string property, string value)
{
    ObjectProperties.SetProperty(property, value, this.LdapPath);
}

ObjectProperties.cs

public static void SetProperty(string property, string value, string objectDn)
{
    bool propertyAlreadyExists = true;
    if (ObjectProperties.AttributeValuesSingleString(property, objectDn) == null) propertyAlreadyExists = false;
    DirectoryEntry child = new DirectoryEntry(objectDn, DomainController.AdUser, DomainController.AdUserPassword);

    //MessageBox.Show(child.Properties[property][0].ToString());
    if (propertyAlreadyExists == false)
    {
        child.Properties[property].Add(value);
    }
    else
    {
        child.Properties[property][0] = value;
    }
    child.CommitChanges();
    child.Close();
}

ISSUE:

The above code works fine when setting a static path such as:
createdUser.HomeDirectory = @"\\domain.local\Data\Home\mustma1";

but there is a caviat with that: When copying a user with a static home path, the new user will get the homedrive of the copied user as well as the permissions to the other users home folder. When setting up the HomeDrive with %UserName% instead, the path will be automatically updated for the new copied user.

There is nothing wrong with the text. I can go into Active Directory Users and Computers, open up the user, remove the % sign and add it again so that the Field gets updated. And voila, it works.

Is there any way to retain that behavior programatically by assigning %UserName% path?

0

There are 0 answers