How to launch ssh-keygen.exe from C# windows form?

compile 21 Reputation points
2021-12-13T14:12:42.103+00:00

Hi,
I want to launch from a button in a Windows Form this command:

    private void buttonGenerateKey_Click(object sender, EventArgs e)
    {
       var workingDir = @"C:\Users\me\Desktop\MyApp\key";
      Directory.CreateDirectory(workingDir);
      Process process = new Process();
      process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
      process.StartInfo.FileName = @"C:\Windows\System32\OpenSSH\ssh-keygen.exe";
     process.StartInfo.Arguments = $"-t ecdsa -b 256 -m pem -N password123 -f \"{Path.Combine(workingDir, "new_ecdsa")}\"";
     process.StartInfo.UseShellExecute = false;
      process.StartInfo.CreateNoWindow = true;
      process.Start();
      process.WaitForExit();
      process.Close();
    }

But, when I click on this button (buttonGenerateKey), an exception occurs: Cannot find specified file: System.ComponentModel.Win32Exception (0x80004005): Cannot find specified file.
in System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
...

the line number is the one corresponding to process.StartInfo.FileName = ....
my App is running as administrator so there shouldn't be any privilege issues. And ssh-keygen.exe exists in C:\Windows\System32\OpenSSH (I've installed OpenSSH).

How I can solve this? I've already tried to:

  • Delete the path before ssh-keygen.exe
  • Copy ssh-keygen.exe in my working dir

But nothing goes right.

Thank you.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 83,206 Reputation points
    2021-12-13T14:26:15.363+00:00

    Add before :

                bool bWow64 = false;
                IsWow64Process(Process.GetCurrentProcess().Handle, out bWow64);
                if (bWow64)
                {
                    IntPtr OldValue = IntPtr.Zero;
                    bool bRet = Wow64DisableWow64FsRedirection(out OldValue);
                }
    

    with :

        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool IsWow64Process(IntPtr hProcess, out bool Wow64Process);
    
        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern bool Wow64DisableWow64FsRedirection(out IntPtr OldValue);
    

0 additional answers

Sort by: Most helpful