如何使用 C# 从 Windows 服务运行 EXE 程序? [英] How can I run an EXE program from a Windows Service using C#?

查看:61
本文介绍了如何使用 C# 从 Windows 服务运行 EXE 程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 C# 从 Windows 服务运行 EXE 程序?

How can I run an EXE program from a Windows Service using C#?

这是我的代码:

System.Diagnostics.Process.Start(@"E:PROJECT XLINI SQLLOADERConsoleApplication2ConsoleApplication2ConsoleApplication2inDebugConsoleApplication2.exe");

当我运行此服务时,应用程序没有启动.
我的代码有什么问题?

When I run this service, the application is not starting.
What's wrong with my code?

推荐答案

这永远行不通,至少在 Windows Vista 或更高版本下不行.关键问题是您试图从 Windows 服务而不是标准 Windows 应用程序中执行此操作.您展示的代码可以在 Windows 窗体、WPF 或控制台应用程序中完美运行,但在 Windows 服务中根本无法运行.

This will never work, at least not under Windows Vista or later. The key problem is that you're trying to execute this from within a Windows Service, rather than a standard Windows application. The code you've shown will work perfectly in a Windows Forms, WPF, or Console application, but it won't work at all in a Windows Service.

Windows 服务无法启动其他应用程序,因为它们没有在任何特定用户的上下文中运行.与常规 Windows 应用程序不同,服务现在在隔离会话中运行并且被禁止与用户或桌面交互.这样就没有地方让应用程序运行了.

Windows Services cannot start additional applications because they are not running in the context of any particular user. Unlike regular Windows applications, services are now run in an isolated session and are prohibited from interacting with a user or the desktop. This leaves no place for the application to be run.

在这些相关问题的答案中提供了更多信息:

More information is available in the answers to these related questions:

正如您现在可能已经想到的那样,解决您的问题的最佳方法是创建一个标准的 Windows 应用程序而不是一个服务.它们旨在由特定用户运行并与该用户的桌面相关联.这样,您就可以随时使用已显示的代码运行其他应用程序.

The best solution to your problem, as you've probably figured out by now, is to create a standard Windows application instead of a service. These are designed to be run by a particular user and are associated with that user's desktop. This way, you can run additional applications whenever you want, using the code that you've already shown.

假设您的控制台应用程序不需要任何类型的接口或输出,另一种可能的解决方案是指示进程不要创建窗口.这将防止 Windows 阻止创建您的进程,因为它将不再请求创建控制台窗口.您可以在这个答案 到一个相关的问题.

Another possible solution, assuming that your Console application does not require an interface or output of any sort, is to instruct the process not to create a window. This will prevent Windows from blocking the creation of your process, because it will no longer request that a Console window be created. You can find the relevant code in this answer to a related question.

这篇关于如何使用 C# 从 Windows 服务运行 EXE 程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆