Process.Start() 未启动 .exe 文件(手动运行时有效)

问题描述 投票:0回答:4

我有一个

.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 时,程序正确运行。但不是通过程序。我看到的是光标转向等待几秒钟然后恢复正常。所以也没有抛出异常。是什么阻止了该文件?

c# exe explorer process.start
4个回答
43
投票

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

就做这样的事情:

processInfo.WorkingDirectory = Path.GetDirectoryName(pathToMyExe);

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


1
投票

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

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

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

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

0
投票

我面临着同样的问题。我正在将我的应用程序作为控制台应用程序运行,当我直接提供文件路径而不使用“Path.GetDirectoryName(pathToMyExe)”时,它工作正常。问题是我已将我的 .Net 应用程序托管为 Windows 服务,但它没有运行当我在 Windows 服务上运行该应用程序时,会运行 exe。

ProcessStartInfo process = new ProcessStartInfo();
            process.FileName = @"C:\ack\Ack_Installer\Ack_Installer\Acc11.exe";
            process.Arguments = arguments;
            process.WindowStyle = ProcessWindowStyle.Maximized;
            process.RedirectStandardOutput = true;
            var pro = Process.Start(process);

© www.soinside.com 2019 - 2024. All rights reserved.