简体   繁体   English

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

[英]Create/run command file programmatically

I'm trying to create a cmd file that will install a .msi and then execute that cmd file via C# code. 我正在尝试创建一个cmd文件,它将安装.msi,然后通过C#代码执行该cmd文件。 The code works perfectly if I run it using f5 or control + f5 from visual studio. 如果我使用Visual Studio中的f5或control + f5运行代码,则代码可以正常运行。

However, once I package up the code in a .msi file and install it (it's a wpf app), when it executes the relevant code, it opens the command window but it doesn't execute the command. 但是,一旦我将代码打包在.msi文件中并安装它(它是一个wpf应用程序),当它执行相关代码时,它会打开命令窗口,但它不会执行命令。 Instead it says: "C:\\Program is not recognized as an internal or external command..." I know this error means that there aren't quotes around a file path but that's not the case, as you can see below the quotes are there. 相反它说:“C:\\ Program不被识别为内部或外部命令......”我知道这个错误意味着文件路径周围没有引号,但事实并非如此,正如您在下面的引号中看到的那样在那儿。 Also, if I go to the program files directory, the Reinstall.cmd file is present and has quotes in it. 此外,如果我转到程序文件目录,则存在Reinstall.cmd文件并在其中包含引号。 I can even double click the generated Reinstall.cmd file and it will execute just fine. 我甚至可以双击生成的Reinstall.cmd文件,它会执行得很好。 What am I missing here?? 我在这里失踪了什么?

Here is the code: 这是代码:

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();
        }

as you can see below the quotes are there. 正如你在下面看到的那样,引号就在那里。

You put them in the first portion, but not where you're executing cmd.exe . 您将它们放在第一部分,但不是您执行cmd.exe

Since your path has spaces in it, you need to wrap it in quotes. 由于您的路径中包含空格,因此需要将其包装在引号中。 Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM