[英]How to close a connection using PrincipalContext to a remote host?
當我執行這段代碼時
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;
}
PrincipalContext
和GroupPrincipal
實現IDisposable
。 確保在使用它們后立即將它們丟棄(當然也可以在嘗試再次連接之前)。 這應該可以解決問題。 例如
簡而言之:
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();
}
PrincipalContext是IDisposible。 您是否嘗試調用Dispose或將代碼放入using塊中?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.