开发者

Changing a limited user account in XP fails

I have the following:

using System;
using System.DirectoryServices.AccountManagement;
public class ChangePassword
{
   public static void Main()
   {    
    PrincipalContext context = new PrincipalContext(ContextType.Machine);
    UserPrincipal user = UserPrincipal.FindByIdentity(context, "someLimitedAccount");
    user.ChangePassword( "xxx", "zzz" );
   }
}

This works just fine with administrator accounts, but seems to crash like so when I try to change limited accounts in XP:

Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
   at ChangePassword.Main()

Is what I am trying to do possible? If so, how?

EDIT #1:

I added the following:

Console.WriteLine( "user: " + user );

Below this line:

UserPrincipal user = UserPrincipal.FindByIdentity(context, "someLimitedAccount");

And I get this:

user:

It doesn't look like user is null when I print it, but then again I'm not really a .Net 开发者_如何学Goguy - I seem to remember this being expected behavior.


Are you sure you have the correct user name? UserPrincipal.FindByIdentity() returns null if there is no match.

With that same kind of code, I'm able to find local Administrator and Limited accounts on both Windows 7 and XP machines (as a .NET 4.0 Client app). It appears to be case insensitive but must be the short name, not the full name. Anything else yields null.

You can get a listing of all local valid user names, you can use the following code:

var pc = new PrincipalContext(ContextType.Machine);
var up = new UserPrincipal(pc);
var users = new PrincipalSearcher(up).FindAll();
foreach (var user in users)
    Console.WriteLine(user);

Combined with the test code:

var pc = new PrincipalContext(ContextType.Machine);
var up = new UserPrincipal(pc);
var users = new PrincipalSearcher(up).FindAll();
foreach (var u in users)
    Console.WriteLine(u.Name);
Console.WriteLine();
Console.Write("User: ");
var name = Console.ReadLine().Trim();
var user = UserPrincipal.FindByIdentity(pc, name);
if (user == null)
    Console.WriteLine("{0} not found", name);
else
{
    Console.WriteLine("Name: {0}", user.Name);
    Console.WriteLine("DisplayName: {0}", user.DisplayName);
}

And some sample outputs

__vmware_user__
Administrator
Guest
Jeff
Share

User: jeff
Name: Jeff
DisplayName: Jeff M
...
User: nonuser
nonuser not found
...
User: guest
Name: Guest
DisplayName:
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜