Create/run command file programmatically

2019-05-06 21:31发布

问题:

I'm trying to create a cmd file that will install a .msi and then execute that cmd file via C# code. The code works perfectly if I run it using f5 or control + f5 from visual studio.

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. 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. Also, if I go to the program files directory, the Reinstall.cmd file is present and has quotes in it. I can even double click the generated Reinstall.cmd file and it will execute just fine. 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();
        }

回答1:

as you can see below the quotes are there.

You put them in the first portion, but not where you're executing 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 + "\"");


标签: c# cmd