Search code examples
c#sharpssh

Error while using sharpSSH in C# for multiple buttons


I have 2 buttons, Connect and Send Command. In the first button I am creating the connection to my server and in the second sending a command. The codes are as below:

public void button1_Click(object sender, EventArgs e)
{
      SshExec shell = new SshExec("hostname", "username", "password");
      shell.Connect();
}

public void button2_Click(object sender, EventArgs e)
{
      shell.RunCommand("ls");
}

Now the error is in "shell.RunCommand("ls");" I am getting "The name 'shell' does not contains in the current context". I am new to C# (mere 2 days) and do not have much idea, so please if anyone can help. What I am expecting is no error and the command to be sent properly to the terminal when the second button is pressed. At the end sorry for bad formatting of the code, please inform me if any additional information is required.


Solution

  • Right now, you are declaring the variable shell inside the button1_Click method. That means only that method can "see" the variable and use it.

    In order for both of the button methods to use the variable, it must be declared outside/above at the class level.

    Try this:

    private SshExec shell;
    
    public void button1_Click(object sender, EventArgs e)
    {
          shell = new SshExec("hostname", "username", "password");
          shell.Connect();
    }
    
    public void button2_Click(object sender, EventArgs e)
    {
          shell.RunCommand("ls");
    }