V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
zxCoder
V2EX  ›  问与答

C#的 ProcessStartInfo 执行命令行指令,可以怎么打印出实际的执行语句吗

  •  
  •   zxCoder · 2021-04-15 20:21:35 +08:00 · 488 次点击
    这是一个创建于 1106 天前的主题,其中的信息可能已经有所发展或是发生改变。

    遇到一个难搞的问题,同样的指令,在命令行可以正常跑,用 c#调用就出问题

    public static string Run(this string cmd) {
                var escapedArgs = cmd.Replace("\"", "\\\"");
                var process = new Process() {
                    StartInfo = new ProcessStartInfo {
                        FileName = "/bin/bash",
                        Arguments = $"-c \"{escapedArgs}\"",
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        CreateNoWindow = true,
                    }
                };
                process.Start();
                var result = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                return Regex.Replace(result, @"[\u0001-\u001F]", "");;
            }
    
    6 条回复    2021-04-16 09:17:59 +08:00
    ReferenceE
        1
    ReferenceE  
       2021-04-15 20:43:42 +08:00 via Android
    建议贴一下错误输出
    zxCoder
        2
    zxCoder  
    OP
       2021-04-15 20:49:19 +08:00
    @ReferenceE 代码没有运行错误,只是我执行的这个脚本命令不能达到预期结果
    ReferenceE
        3
    ReferenceE  
       2021-04-15 23:36:25 +08:00 via Android
    @zxCoder ...
    ysc3839
        4
    ysc3839  
       2021-04-15 23:43:51 +08:00 via Android
    把脚本发来看看吧
    msg7086
        5
    msg7086  
       2021-04-16 05:27:09 +08:00
    你写个脚本,把传入的 argv 全部打印出来看看不就知道哪里不一样了。
    最终系统执行的语句也不是字符串而是数组,字符串是要经过 Shell 解析成数组的。
    比如说在 bash 下运行 ls -l /u* 的话,实际执行的是 ['ls', '-l', '/usr'] 。
    zxCoder
        6
    zxCoder  
    OP
       2021-04-16 09:17:59 +08:00
    @msg7086

    “你写个脚本,把传入的 argv 全部打印出来看看不就知道哪里不一样了。”

    请问这个具体是什么意思
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4235 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 05:32 · PVG 13:32 · LAX 22:32 · JFK 01:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.