当我执行此代码时,
PrincipalContext oPrincipalContext = new PrincipalContext(
ContextType.Machine,
computer.Name,
null,
ContextOptions.Negotiate,
Settings.UserName,
Settings.UserPassword))
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(
oPrincipalContext,
Settings.AdministratorsGroup);
创建与远程计算机的连接。我能够看到它在cmd.exe中编写“net use”。
但在关闭我的应用程序之前,我不知道如何关闭此连接。
退出我的应用时会自动关闭。
这是我的方法:
public Dictionary<Principal, ComputerPrincipal>
GetMembersOfAdministratorsGroup(ComputerPrincipal computer)
{
var usersList = new Dictionary<Principal, ComputerPrincipal>();
var tempUsersList = new Dictionary<string, Principal>();
using (PrincipalContext oPrincipalContext =
new PrincipalContext(
ContextType.Machine,
computer.Name,
null,
ContextOptions.Negotiate,
Settings.UserName,
Settings.UserPassword))
{
using (GroupPrincipal oGroupPrincipal =
GroupPrincipal.FindByIdentity(
oPrincipalContext,
Settings.AdministratorsGroup))
{
if (oGroupPrincipal != null)
{
var result = oGroupPrincipal.GetMembers();
foreach (Principal user in result)
{
if (!tempUsersList.ContainsKey(user.Name))
{
tempUsersList.Add(user.Name, user);
usersList.Add(user, computer);
}
}
}
}
}
return usersList;
}
答案 0 :(得分:3)
PrincipalContext
和GroupPrincipal
都实施IDisposable
。确保在使用它们之后立即将它们丢弃(当然在再次尝试连接之前)。这应该可以解决问题。 E.g。
简写: -
using(PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer.Name, null, ContextOptions.Negotiate, Settings.UserName, Settings.UserPassword))
using(GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, Settings.AdministratorsGroup))
{
// perform operations here
}
或以长手: -
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer.Name, null, ContextOptions.Negotiate, Settings.UserName, Settings.UserPassword);
try
{
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, Settings.AdministratorsGroup);
try
{
// perform operations here
}
finally
{
oGroupPrincipal.Dispose();
}
}
finally
{
oPrincipalContext.Dispose();
}
答案 1 :(得分:0)
PrincipalContext是IDisposible。您是否尝试过调用Dispose或将代码放入使用块?