以编程方式创建/运行命令文件

我正在尝试创建一个cmd文件,它将安装.msi,然后通过C#代码执行该cmd文件。 如果我使用Visual Studio中的f5或control + f5运行它,代码可以正常工作。

但是,一旦我将代码打包在.msi文件中并安装它(它是一个wpf应用程序),当它执行相关代码时,它会打开命令窗口,但它不会执行命令。 相反它说:“C:\ Program不被识别为内部或外部命令……”我知道这个错误意味着文件路径周围没有引号,但事实并非如此,正如您在下面的引号中看到的那样在那儿。 此外,如果我转到程序文件目录,则存在Reinstall.cmd文件并在其中包含引号。 我甚至可以双击生成的Reinstall.cmd文件,它会执行得很好。 我在这里想念的是什么?

这是代码:

private string MSIFilePath = Path.Combine(Environment.CurrentDirectory, "HoustersCrawler.msi"); private string CmdFilePath = Path.Combine(Environment.CurrentDirectory, "Reinstall.cmd"); private void CreateCmdFile() { //check if file exists. if (File.Exists(CmdFilePath)) File.Delete(CmdFilePath); //create new file. var fi = new FileInfo(CmdFilePath); var fileStream = fi.Create(); fileStream.Close(); //write commands to file. using (TextWriter writer = new StreamWriter(CmdFilePath)) { writer.WriteLine(String.Format("msiexec /i \"{0}\"", MSIFilePath));// /quiet } } private void RunCmdFile() {//run command file to reinstall app. var p = new Process(); p.StartInfo = new ProcessStartInfo("cmd.exe", "/k " + CmdFilePath); p.Start(); p.WaitForExit(); } 

正如你在下面看到的那样,引号就在那里。

您将它们放在第一部分,但不是您执行cmd.exe

由于您的路径中包含空格,因此需要将其包装在引号中。 尝试:

 p.StartInfo = new ProcessStartInfo("cmd.exe", "/k \"" + CmdFilePath + "\"");