Process.Start() not starting the .exe file (works when run manually)

五迷三道 提交于 2019-12-04 01:38:28

You are not setting the working directory path, and unlike when starting the application through Explorer, it isn't set automatically to the location of the executable.

Just do something like this:

processInfo.WorkingDirectory = Path.GetDirectoryName(pathToMyExe);

(assuming the input files, DLLs etc. are in that directory)

    private void Print(string pdfFileName)
    {
        string processFilename = Microsoft.Win32.Registry.LocalMachine
    .OpenSubKey("Software")
    .OpenSubKey("Microsoft")
    .OpenSubKey("Windows")
    .OpenSubKey("CurrentVersion")
    .OpenSubKey("App Paths")
    .OpenSubKey("AcroRd32.exe")
    .GetValue(string.Empty).ToString();

        ProcessStartInfo info = new ProcessStartInfo();
        info.Verb = "print";
        info.FileName = processFilename;
        info.Arguments = string.Format("/p /h {0}", pdfFileName);
        info.CreateNoWindow = true;
        info.WindowStyle = ProcessWindowStyle.Hidden;
        ////(It won't be hidden anyway... thanks Adobe!)
        info.UseShellExecute = false;

        Process p = Process.Start(info);
        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

        int counter = 0;
        while (!p.HasExited)
        {
            System.Threading.Thread.Sleep(1000);
            counter += 1;

            if (counter == 5)
            {
                break;
            }
        }

        if (!p.HasExited)
        {
            p.CloseMainWindow();
            p.Kill();
        }
    }
Payam Lashkari

Due to different working directory, you have to set your working directory properly to the path that you want your process to start.

A sample demonstration of this can be:

Process process = new Process()
{
    StartInfo = new ProcessStartInfo(path, "{Arguments If Needed}")
    {
        WindowStyle = ProcessWindowStyle.Normal,
        WorkingDirectory = Path.GetDirectoryName(path)
    }
};

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