I have triying to send ssh commands to my CPU using Renci and sshnet libraries by clicking two buttons. First button, it works fine but when i clicked the second, it says
'System.ObjectDisposedException'
for client At those rows.
client.Connect();
shCommand cmd3 = client.RunCommand("ls -la checkEth*");
Could anyone help?
public partial class Form1 : Form
{
SshClient client = new SshClient("192.168.1.5", "deneme", "deneme");
int milliseconds;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Button 1 clicked");
using (client)
{
milliseconds = 200;
Thread.Sleep(milliseconds);
client.Connect();
SshCommand cmd = client.RunCommand("ls > checkEth.txt");
System.Diagnostics.Debug.WriteLine("chechethYapildi 1: " + cmd.Result);
Thread.Sleep(milliseconds);
SshCommand cmd2 = client.RunCommand("ls -la checkEth*");
System.Diagnostics.Debug.WriteLine("com 1:" + cmd2.Result);
textBox1.Text = (cmd2.Result);
System.Diagnostics.Debug.WriteLine("cevapgelecek");
//client.Dispose();
}
client.Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
using (client)
{
client.Connect();
SshCommand cmd3 = client.RunCommand("ls -la checkEth*");
textBox1.Text = (cmd3.Result);
System.Diagnostics.Debug.WriteLine("ikinci butona basıldı");
}
}
}
I found the solution. When I am using "using(client)", I dispose the client. Because of disposing, button2_Click won't be able to connect the same client. My new code is below.
public partial class Form1 : Form
{
SshClient client = new SshClient("192.168.1.5", "deneme", "deneme");
int milliseconds;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("Button 1 clicked");
milliseconds = 200;
Thread.Sleep(milliseconds);
client.Connect();
SshCommand cmd = client.RunCommand("ls > checkEth.txt");
System.Diagnostics.Debug.WriteLine("chechethYapildi 1: " + cmd.Result);
Thread.Sleep(milliseconds);
SshCommand cmd2 = client.RunCommand("ls -la checkEth*");
System.Diagnostics.Debug.WriteLine("com 1:" + cmd2.Result);
textBox1.Text = (cmd2.Result);
System.Diagnostics.Debug.WriteLine("cevapgelecek");
}
private void button2_Click(object sender, EventArgs e)
{
SshCommand cmd3 = client.RunCommand("ls -la checkEth*");
textBox1.Text = (cmd3.Result);
System.Diagnostics.Debug.WriteLine("ikinci butona basıldı");
}
}
You're reusing the same client
object in both button event methods. Each method contains a using statement, which will cause Dispose
method to be called when control leaves the using block. A client that has already been disposed cannot be reused.
You need to either dispose the client elsewhere, or create a new client in each event handler, and dispose it as you do now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.