【发布时间】:2012-11-06 21:03:16
【问题描述】:
在我的控制台应用程序中,我需要执行一系列命令:
D:
cd d:\datafeeds
grp -encrypt -myfile.xls
这组命令实际上是使用工具 (gpg) 加密文件。
我该怎么做?
【问题讨论】:
标签: c# command-prompt
在我的控制台应用程序中,我需要执行一系列命令:
D:
cd d:\datafeeds
grp -encrypt -myfile.xls
这组命令实际上是使用工具 (gpg) 加密文件。
我该怎么做?
【问题讨论】:
标签: c# command-prompt
你可以创建一个进程。要使用它,请在 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";
【讨论】:
其他答案没有提到设置工作目录的能力。这消除了对目录更改操作的需要以及将可执行文件存储在 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();
【讨论】:
创建一个包含您的命令的批处理文件。
然后使用 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 属性对所有内容进行编码。当您必须更改某些内容并且您没有可用的代码时,它会更加灵活。
【讨论】:
Process.start 让您可以在 shell 中执行命令。
【讨论】: