J. Wenston
J. Wenston

Reputation: 5

How to use %username% variable in Active Directory user paths using C#?

I developed an Active Directory user management tool in C# that does some things automatically. This is better for my particular case than the "Active Directory Users and Computers" tool from Microsoft. I have to use roaming profiles and home directories which contain the username of a user.

Now I want to change the username of a user with my program in C#. Everything works fine, but I want to use the "%username%" variable instead of putting the new username directly into these paths (home directory and roaming profile), because, by using the variable, I ensure that the new username will be placed into these paths if I copy the user object using Microsoft's AD management tool (right click --> "copy").

If I enter "%username%" when creating or editing a user with Microsoft's AD tool, this variable gets replaced by the username, so it works. But if I put this variable into a path using C#, it just puts the string "%username%" at the end of the path (e.g. "\fileserver1\UserHomes\%username%"). It doesn't replace it with the actual username and "stores" that placeholder.

How can I use this variable within my C# code properly, so that it get's replaced with the actual username?

I'm using this code (reduced, it's just an example) to change the users username (SamAccountName) and, for example, the home directory. "user" is my UserPrincipal object. Of course, I'm renaming the actual folder after this:

[...]
string newUsername = "NewUsername"; // New username

user.SamAccountName = newUsername;
user.UserPrincipalName = $"{ newUsername }@{ domain }";
user.HomeDirectory = "\\fileserver1\UserHomes\%username%";

user.Save(); // Save changes

Upvotes: 0

Views: 10658

Answers (2)

Ashigore
Ashigore

Reputation: 4678

The %username% environment variable and the one used AD Users and Computers is not the same. AD Users and Computers replaces it with the actual username value immediately when you click OK. It is not something that AD understands, just a token used by the AD Users and Computers application.

Considering you already constructed a string using the username, you shouldn't find it hard to fix this.

user.HomeDirectory = $"\\fileserver1\UserHomes\{newUsername}";

Also powershell would probably be more appropriate for something like this.

Upvotes: 0

Related Questions