I am attempting to start an MSTSC / RDP session from C#. For various reasons I've settled on invoking Powershell to do this, partly because I know the powershell commands work, although I wouldn't be averse to attempting other methods to start the session. I have RDSH enabled and am happily able to start multiple RDP sessions on this machine.
Running the following command in Powershell starts the RDP session exactly as I would expect:
cmdkey /generic:TERMSRV/localhost /user:username /pass:password; mstsc /v:localhost
Attempting to translate this to C# using the code below and System.Management.Automation.dll however fails with the error:
Invalid connection file (True) specified
Please note that this is a Remote Desktop Connection error, not a powershell or C# error.
The code I am using is:
void StartRDP(string username, string password)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
// create cached credential to use for remote session
PowerShellInstance.AddCommand("cmdkey");
PowerShellInstance.AddParameter("/generic:TERMSRV/localhost");
PowerShellInstance.AddParameter("/user:" + username);
PowerShellInstance.AddParameter("/pass:" + password);
// append mstsc command
PowerShellInstance.AddStatement();
// start remote desktop connection to localhost
PowerShellInstance.AddCommand("mstsc");
PowerShellInstance.AddParameter("/v:localhost");
// invoke command, creating credential and starting mstsc
PowerShellInstance.Invoke();
}
}
This is called using:
StartRDP(username, password);
I have also tested it with hardcoded variables with the same result. Any advice much appreciated!
Edit: Having inspected the credentials cached on the system, I can see that this method is appending "True" to the end of all the parameters... see the difference between a credential created directly in Powershell and one created in C#:
Powershell:
Target: LegacyGeneric:target=TERMSRV/localhost
Type: Generic
User: username
C#:
Target: LegacyGeneric:target=TERMSRV/localhost True
Type: Generic
User: username True
This seems to be the issue, although I am no closer to solving it.