C# 外部类库调用时无法访问已释放的对象错误
我有一个Windows窗体应用程序,它使用Powershell和Exchange2007 cmdlet在Exchange中设置用户帐户。此应用程序只有一个表单可以获取新用户的信息,然后运行Powershell命令。像一个优秀的程序员一样,我只是对代码进行了重构,将所有Exchange和Active Directory调用放在不同的类中。在Windows窗体中,我在按钮单击事件中调用以下代码:C# 外部类库调用时无法访问已释放的对象错误,c#,powershell,exchange-server-2007,cmdlets,C#,Powershell,Exchange Server 2007,Cmdlets,我有一个Windows窗体应用程序,它使用Powershell和Exchange2007 cmdlet在Exchange中设置用户帐户。此应用程序只有一个表单可以获取新用户的信息,然后运行Powershell命令。像一个优秀的程序员一样,我只是对代码进行了重构,将所有Exchange和Active Directory调用放在不同的类中。在Windows窗体中,我在按钮单击事件中调用以下代码: ExchangeMailboxFunctions exFuncs = new ExchangeMailb
ExchangeMailboxFunctions exFuncs = new ExchangeMailboxFunctions();
exFuncs.CreateNewMailbox(username, userPrincipalName, OU, txtDisplayName.Text, txtFirstName.Text, txtInitials.Text, txtLastName.Text,
txtPassword1.Text, ckbUserChangePassword.Checked, mailboxLocation);
在课堂上,我有以下几点:
RunspaceConfiguration config = RunspaceConfiguration.Create();
PSSnapInException warning;
Runspace thisRunspace;
public ExchangeMailboxFunctions()
{
InitializePowershell();
}
private void InitializePowershell()
{
try
{
thisRunspace = RunspaceFactory.CreateRunspace(config);
config.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out warning);
thisRunspace.Open();
}
catch (Exception ex)
{
throw new Exception(string.Format("Could not initialize Powershell: {0}", ex.Message));
}
}
public void CreateNewMailbox(string username, string userPrincipalName, string OU, string DisplayName, string FirstName, string Initials,
string LastName, string Password, bool ChangePasswordNextLogon, string MailboxLocation)
{
try
{
using (Pipeline thisPipeline = thisRunspace.CreatePipeline())
[Set a bunch of pipLine parameters here]
thisPipeline.Invoke();
}
catch (Exception ex)
调用导致错误,我不知道处理了什么。当该代码位于表单的codebehind中时,它工作得非常好。我也有一些Active Directory方法,我把它们放到一个单独的类库中,它们似乎工作得很好
我该怎么做才能让这一切停止?谢谢 确保您的代码实际上是这样的
using (Pipeline thisPipeline = thisRunspace.CreatePipeline())
{
[Set a bunch of pipLine parameters here]
thisPipeline.Invoke();
}
括号是关键,你的例子中没有括号。对不起,伙计们,括号之类的东西实际上没问题——我一定是把它们排除在问题之外了。我在create方法中遗漏了以下几行代码:
using (SecureString ss = new SecureString())
{
foreach (char c in Password)
ss.AppendChar(c);
thisPipeline.Commands[0].Parameters.Add("Password", ss);
}
由于在调用调用之前已释放Using,因此没有ss,因为它已被释放。在发布这篇文章之前,我们应该更深入地了解一下:-(是的,这就是正在发生的事情。该函数似乎还缺少另一个“}”。