【问题标题】:Want to execute a command in command prompt window想要在命令提示符窗口中执行命令
【发布时间】:2012-11-06 21:03:16
【问题描述】:

在我的控制台应用程序中,我需要执行一系列命令:

D:
cd d:\datafeeds
grp -encrypt -myfile.xls

这组命令实际上是使用工具 (gpg) 加密文件。
我该怎么做?

【问题讨论】:

    标签: c# command-prompt


    【解决方案1】:

    你可以创建一个进程。要使用它,请在 grp 所在的文件夹中执行生成的 .exe。

     Process process1 = new Process();
     process1.StartInfo.UseShellExecute = false;
     process1.StartInfo.RedirectStandardOutput = true;
     process1.StartInfo.FileName = "cmd.exe";
     process1.StartInfo.Arguments = "/C grp -encrypt -myfile.xls";
    

    【讨论】:

    • 我想通过将 "d:\datafeeds" 作为当前文件夹来执行它,因为 gpg 只会在当前文件夹中查找文件。
    【解决方案2】:

    其他答案没有提到设置工作目录的能力。这消除了对目录更改操作的需要以及将可执行文件存储在 datafeeds 目录中的需要:

    Process proc = new Process();
    proc.StartInfo.WorkingDirectory = "D:\\datafeeds";
    proc.StartInfo.FileName = "grp";
    proc.StartInfo.Arguments = "-encrypt -myfile.xls";
    proc.Start();
    
    // Comment this out if you don't want to wait for the process to exit.
    proc.WaitForExit();
    

    【讨论】:

      【解决方案3】:

      创建一个包含您的命令的批处理文件。
      然后使用 Process.Start 和 ProcessStartInfo 类来执行你的批处理。

        ProcessStartInfo psi = new ProcessStartInfo(@"d:\datafeeds\yourbatch.cmd");
        psi.WindowStyle = ProcessWindowStyle.Minimized;
        psi.WorkingDirectory = @"d:\datafeeds";
        Process.Start(psi);
      

      ProcessStartInfo 包含其他有用的属性See MSDN docs
      Process 和 ProcessStartInfo 需要 using System.Diagnostics;

      在这种情况下(当您需要运行命令行工具时),我更喜欢使用批处理方法,而不是通过 ProcessStartInfo 属性对所有内容进行编码。当您必须更改某些内容并且您没有可用的代码时,它会更加灵活。

      【讨论】:

        【解决方案4】:

        Process.start 让您可以在 shell 中执行命令。

        看到这个问题:ShellExecute equivalent in .NET

        【讨论】:

        • 是的,但对我来说,它不是像复制等这样的单个命令。它是一个 3 步过程。
        • 然后你运行几个进程。结果将在目录中。或检查这个问题:stackoverflow.com/questions/437419/…
        猜你喜欢
        • 1970-01-01
        • 2011-10-26
        • 2020-11-24
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-11
        • 1970-01-01
        相关资源
        最近更新 更多