Create/run command file programmatically

情到浓时终转凉″ 提交于 2020-01-23 08:33:15

问题


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 + "\"");


来源:https://stackoverflow.com/questions/4910954/create-run-command-file-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!