You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Winform将远程桌面连接设置保存为RDP文件的方法及代码咨询

C# 实现RDP便携连接生成工具示例

以下是Windows平台下的实现代码,可直接用于WinForm项目,生成的文件双击即可直接登录远程主机,无需二次输入凭证:

核心依赖

需要先引用System.Security程序集,用于调用Windows原生加密接口加密RDP密码。

完整代码

using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace RdpClientGenerator
{
    // RDP文件生成工具类
    public static class RdpBuilder
    {
        [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool CryptProtectData(ref DATA_BLOB pDataIn, string szDataDescr, ref DATA_BLOB pOptionalEntropy, IntPtr pvReserved, IntPtr pPromptStruct, uint dwFlags, ref DATA_BLOB pDataOut);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct DATA_BLOB
        {
            public int cbData;
            public IntPtr pbData;
        }

        // 加密RDP密码为标准rdp文件可识别格式
        private static string EncryptPassword(string rawPwd)
        {
            byte[] pwdBytes = Encoding.Unicode.GetBytes(rawPwd);
            DATA_BLOB inputBlob = new DATA_BLOB { cbData = pwdBytes.Length, pbData = Marshal.AllocHGlobal(pwdBytes.Length) };
            Marshal.Copy(pwdBytes, 0, inputBlob.pbData, pwdBytes.Length);
            DATA_BLOB entropyBlob = new DATA_BLOB();
            DATA_BLOB outputBlob = new DATA_BLOB();

            try
            {
                if (CryptProtectData(ref inputBlob, null, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, 1, ref outputBlob))
                {
                    byte[] encryptedBytes = new byte[outputBlob.cbData];
                    Marshal.Copy(outputBlob.pbData, encryptedBytes, 0, outputBlob.cbData);
                    return BitConverter.ToString(encryptedBytes).Replace("-", string.Empty);
                }
                return string.Empty;
            }
            finally
            {
                if (inputBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(inputBlob.pbData);
                if (outputBlob.pbData != IntPtr.Zero) Marshal.FreeHGlobal(outputBlob.pbData);
            }
        }

        // 生成RDP连接文件到指定路径
        public static bool BuildRdpFile(string savePath, string host, int port, string username, string password)
        {
            if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(username)) return false;
            string encryptedPwd = EncryptPassword(password);
            StringBuilder rdpContent = new StringBuilder();
            rdpContent.AppendLine($"full address:s:{host}:{port}");
            rdpContent.AppendLine($"username:s:{username}");
            rdpContent.AppendLine($"password 51:b:{encryptedPwd}");
            rdpContent.AppendLine("screen mode id:i:2"); // 默认全屏启动
            rdpContent.AppendLine("desktopwidth:i:1920");
            rdpContent.AppendLine("desktopheight:i:1080");
            rdpContent.AppendLine("prompt for credentials:i:0"); // 关闭凭证弹窗
            rdpContent.AppendLine("authentication level:i:2");
            rdpContent.AppendLine("auto connect:i:1");
            rdpContent.AppendLine("negotiate security layer:i:1");

            try
            {
                File.WriteAllText(savePath, rdpContent.ToString(), Encoding.UTF8);
                return true;
            }
            catch { return false; }
        }
    }

    // 窗口逻辑
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            // 默认端口填3389
            txtPort.Text = "3389";
        }

        // 创建按钮点击事件
        private void btnCreate_Click(object sender, EventArgs e)
        {
            string connectName = txtConnectName.Text.Trim();
            string host = txtHost.Text.Trim();
            int port = int.TryParse(txtPort.Text.Trim(), out int p) ? p : 3389;
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text;

            if (string.IsNullOrEmpty(connectName) || string.IsNullOrEmpty(host) || string.IsNullOrEmpty(username))
            {
                MessageBox.Show("请补全连接名称、主机地址、用户名三项必填信息");
                return;
            }

            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string savePath = Path.Combine(desktopPath, $"{connectName}.rdp");

            bool result = RdpBuilder.BuildRdpFile(savePath, host, port, username, password);
            MessageBox.Show(result ? "连接文件已生成到桌面,双击即可直接登录" : "生成失败,请检查输入信息");
        }
    }
}

补充说明

  • 生成的.rdp文件默认关联系统远程桌面工具mstsc,双击即可直接启动连接
  • 密码采用Windows当前用户上下文加密,仅当前设备当前登录用户可使用,符合RDP安全规范
  • 如果需要自定义生成文件的图标,可通过COM接口生成.lnk快捷方式指向rdp文件,再给快捷方式设置自定义图标即可
  • 如需制作跨设备可用的便携版本,可将配置参数内置到exe中,运行时动态生成临时rdp文件调用mstsc,启动完成后自动删除临时文件即可

内容的提问来源于stack exchange,提问作者mstftncl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:36:03