【问题标题】:Process.Start() not starting the .exe file (works when run manually)Process.Start() 未启动 .exe 文件(手动运行时有效)
【发布时间】:2015-10-17 09:25:36
【问题描述】:

我有一个.exe 文件,需要在创建文件后运行。该文件已成功创建,之后我使用以下代码运行.exe 文件:

ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = pathToMyExe;
processInfo.ErrorDialog = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;                        
Process proc = Process.Start(processInfo);

我也尝试了一个简单的Process.Start(pathToMyExe);,但.exe 文件没有运行。当我在 Windows Explorer 上手动尝试 pathToMyExe 时,程序正确运行。但不是通过程序。我看到的是光标变成等待几秒钟然后恢复正常。所以也没有抛出异常。是什么阻止了文件?

【问题讨论】:

  • 我的精神力量告诉我你需要设置WorkingDirectory
  • 确定它没有运行?您重定向了标准输出,但没有发布任何与处理重定向输出相关的代码。因此,除非您特别处理,否则您将看不到任何输出。我假设这是一个控制台应用程序。
  • @Luaan 你是对的。您可以将其发布为答案。

标签: c# exe explorer process.start


【解决方案1】:
    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();
        }
    }

【讨论】:

    【解决方案2】:

    由于工作目录不同,您必须将工作目录正确设置为您希望进程启动的路径。

    这方面的示例演示可以是:

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

    【讨论】:

      【解决方案3】:

      您没有设置工作目录路径,并且与通过资源管理器启动应用程序不同,它不会自动设置为可执行文件的位置。

      只要做这样的事情:

      processInfo.WorkingDirectory = Path.GetDirectoryName(pathToMyExe);
      

      (假设输入文件、DLL 等在该目录中)

      【讨论】:

      • processInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
      猜你喜欢
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多