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

C#中无法运行路径含空格的EXE程序命令问题

解决含空格路径的命令执行问题

问题根源

通过cmd.exe /k传递带引号的命令时,外层引号会被cmd解析时剥离,导致含空格的路径被截断,触发'C:\Program' 不是内部或外部命令的错误。

修复方案

直接指定目标程序为FileName,而非通过cmd.exe中转,同时单独处理参数和输出重定向:

修改后的代码

static void Main(string[] args)
{
    // 导出当前设置
    string cncmd = GetCnCMD();
    string AMD3D = Path.Combine(System.IO.Path.GetTempPath(), "AMD3DSettings.zip");
    string logPath = Path.Combine(System.IO.Path.GetTempPath(), "Log3d.txt");

    Run(cncmd, $"export \"{AMD3D}\"", logPath);
}

static void Run(string exePath, string arguments, string logFilePath)
{
    Console.WriteLine($"命令:\"{exePath}\" {arguments} > {logFilePath}");

    using (System.Diagnostics.Process process = new System.Diagnostics.Process())
    {
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
        startInfo.FileName = exePath;
        startInfo.Arguments = arguments;
        // 配置输出重定向到日志文件
        startInfo.RedirectStandardOutput = true;
        startInfo.UseShellExecute = false;

        process.StartInfo = startInfo;
        process.Start();

        // 将程序输出写入日志文件
        using (StreamWriter writer = new StreamWriter(logFilePath))
        {
            writer.Write(process.StandardOutput.ReadToEnd());
        }

        process.WaitForExit();
    }
}

// 保留原GetCnCMD方法不变
public static string GetCnCMD()
{
    try
    {
        RegistryKey HKLM = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
        RegistryKey cnkey = HKLM.OpenSubKey(@"SOFTWARE\AMD\CN");

        string dir = (string) cnkey.GetValue("InstallDir");

        if (dir.EndsWith(@"\") || dir.EndsWith(@"/"))
        {
            dir = dir.Substring(0, dir.Length - 1);
        }

        return dir + @"\cncmd.exe";
    }
    catch(Exception e)
    {
        Console.Error.WriteLine($"{e.Message} {e.GetType()}");
        string HOMEDRIVE = Environment.GetFolderPath(Environment.SpecialFolder.System).Substring(0, 1);
        string cncmd = HOMEDRIVE + @":\Program Files\AMD\CNext\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;

        cncmd = HOMEDRIVE + @":\Program Files (x86)\AMD\CNext\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;

        // 检查新旧版本可能的路径
        cncmd = HOMEDRIVE + @":\Program Files\AMD\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;

        cncmd = HOMEDRIVE + @":\Program Files (x86)\AMD\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;
    }

    return null;
}

关键修改点

  • 直接调用目标程序:不再通过cmd.exe中转,将cncmd.exe直接设为FileName,避免cmd解析引号时的问题
  • 单独处理参数:将命令参数拆分到Arguments属性中,.NET会自动处理含空格路径的引号包裹
  • 路径优化:用Path.Combine替代字符串拼接,避免手动处理路径分隔符的错误
  • 资源释放:使用using语句确保进程和文件流资源被正确释放
  • 输出重定向:通过RedirectStandardOutput手动将程序输出写入日志文件,替代cmd的>重定向语法

原问题信息

问题描述

尝试通过Visual Studio 2017中的C#代码执行命令,目标框架为.NET 4.5。因EXE文件路径含空格,无论用引号包裹都无法成功执行,参考他人方案也无效。系统版本为Windows 10.0.19045.4046。

原代码

static void Main(string[] args)
{
    // Export Current Settings
    string cncmd = GetCnCMD();
    string AMD3D = (System.IO.Path.GetTempPath() + @"\AMD3DSettings.zip").Replace(@"\\", @"\");

    Run("\"" + cncmd + "\" export \"" + AMD3D + "\" >%TMP%\\Log3d.txt");
}

static void Run(string command)
{
    Console.WriteLine(command);

    System.Diagnostics.Process process = new System.Diagnostics.Process();

    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
    startInfo.FileName = @"cmd.exe";
    startInfo.Arguments = "/k " + command;

    process.StartInfo = startInfo;
    process.Start();
    process.WaitForExit();
}

public static string GetCnCMD()
{
    try
    {
        RegistryKey HKLM = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
        RegistryKey cnkey = HKLM.OpenSubKey(@"SOFTWARE\AMD\CN");

        string dir = (string) cnkey.GetValue("InstallDir");

        if (dir.EndsWith(@"\") || dir.EndsWith(@"/"))
        {
            dir = dir.Substring(0, dir.Length - 1);
        }

        return dir + @"\cncmd.exe";
    }
    catch(Exception e)
    {
        Console.Error.WriteLine(e.Message + " " + e.GetType());
        string HOMEDRIVE = Environment.GetFolderPath(Environment.SpecialFolder.System).Substring(0, 1);
        string cncmd = HOMEDRIVE + @":\Program Files\AMD\CNext\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;

        cncmd = HOMEDRIVE + @":\Program Files (x86)\AMD\CNext\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;

        // Check older or newer likely paths
        cncmd = HOMEDRIVE + @":\Program Files\AMD\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;

        cncmd = HOMEDRIVE + @":\Program Files (x86)\AMD\CNext\cncmd.exe";

        if (File.Exists(cncmd))
            return cncmd;
    }

    return null;
}

命令行输出

  1. 打印的命令:
"C:\Program Files\AMD\CNext\CNext\cncmd.exe" export "C:\Users\jredfox\AppData\Local\Temp\AMD3DSettings.zip" >%TMP%\Log3d.txt
  1. 错误提示:

'C:\Program' 不是内部或外部命令,也不是可运行的程序或批处理文件。


内容的提问来源于stack exchange,提问作者OW2 Is Trash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:08:26