Search code examples
c#windows-7remote-desktopmstsc

Connecting and logging in to a remote desktop using C# / Windows7


I would like to write an application which allows users to enter their login credentials for a machine in our company network and then connect them to that machine. Apparently, the log in credentials for remote desktop connections are not saved in the *.RDP files anymore in Windows7 (and Vista?), so this approach does not work. I know that I can view the saved credentials using rundll32 keymgr.dll,KRShowKeyMgr, but not how to add credentials to this storage programmatically. Any pointers or even code examples (preferably in C#, but anything goes) would be greatly appreciated.


Solution

  • You can still put the password in the .rdp file, it will still honor them - unless there is a group policy setting to explicitly ignore it.

    EDIT:

    For what it's worth, that article is a bit over-kill. There is a managed wrapper around all that messy P/Invoke business. There are simpler ways to do it if you are using .NET 2.0 using the ProtectedData class. (Start by adding a reference to the System.Security assembly).

    Once you've got that reference added, you can do this:

    public string Encrypt(string toEncrypt)
    {
        var userData = Encoding.Unicode.GetBytes(toEncrypt ?? String.Empty);
        return "password 51:b:" + ToHexString(ProtectedData.Protect(userData, new byte[0], DataProtectionScope.CurrentUser));
    }
    
    private static string ToHexString(byte[] bytes)
    {
        if (bytes == null)
        {
            return String.Empty;
        }
        return bytes.Aggregate(new StringBuilder(), (sb, b) => sb.AppendFormat("{0:x2}", b)).ToString();
    }
    

    And that's it.