从Windows服务访问环境变量 [英] Accessing Environment Variables from Windows Services

查看:499
本文介绍了从Windows服务访问环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C#编写Windows服务。我需要找到的路径到一定文件,该文件存储在一个环境变量。在一个常规的C#控制台应用程序,我可以做到这一点与以下行:

I am attempting to write a Windows Service in C#. I need to find the path to a certain file, which is stored in an environment variable. In a regular C# console application, I can achieve that with the following line:

string t = System.Environment.GetEnvironmentVariable("TIP_HOME");

如果我写的控制台我看到它是成功的。

If I write that to the console I see that it was successful.

现在,如果我尝试在一个Windows服务相同的代码,字符串 T 是空的。

Now, if I try that same code in a Windows Service, the string t is empty.

任何想法,为什么?

推荐答案

我不知道这是否是有用的,但我发现,对于每个服务,有直接添加环境变量的服务的选项。

I've no idea if this is useful, but I've found that for every service, there is an option to add environment variables directly to a service.

据通过注册表进行。

说关键看你的服务是...

Say the key to your service is ...

HKLM\SYSTEM\CurrentControlSet\Services\YourService

HKLM\SYSTEM\CurrentControlSet\Services\YourService

创建一个名为REG_MULTI_SZ环境。

Create a REG_MULTI_SZ called Environment.

现在你可以添加喜欢...

Now you can add entries like ...

Var1=Value1
Var2=Value2

而这些将提供给服务代码。

and these will be available to the service code.

如果您使用的是Windows资源工具包安装脚本作为一种服务(INSTSRV.EXE和SRVANY.EXE),然后再次,你必须设置环境变量的服务选项,但最有可能是错误的,因为这些将是SRVANY.EXE。

If you are using the Windows Resource ToolKit to install scripts as a service (instsrv.exe and srvany.exe), then, again, you have the option of setting Environment variables for the service, but most likely it is the wrong one as these would be for srvany.exe.

相反,使用密钥...

Instead, you use the key ...

HKLM\SYSTEM\CurrentControlSet\Services\YourService\Parameters

HKLM\SYSTEM\CurrentControlSet\Services\YourService\Parameters

和创建一个名为AppEnvironment REG_MULTI_SZ

and create a REG_MULTI_SZ called AppEnvironment

设置以同样的方式的项目。

Set the entries in the same way.

而现在你的脚本服务都有它自己的环境变量。

And now your script service has it's own environment variables.

我使用这些技术用PHP + WINCACHE让我设置唯一的每个允许WINCACHE共享一个中央服务的APP_POOL_ID缓存(基于APP_POOL_ID)的所有线程(使用WShell推出非阻塞子线程,仍然共享相同的WINCACHE作为发射器,允许简单,进程间通信)。

I'm using these techniques with PHP+WinCache to allow me to set an APP_POOL_ID unique to each service which allows WinCache to share a central cache (based upon APP_POOL_ID) for all "threads" (using WShell to launch non-blocking child "threads" and still share the same WinCache as the launcher, allowing simplistic, inter-process communication).

反正。我希望这有助于一些。

Anyway. I hope this helps somewhat.

我认为,在主,你是不是增加不必要的env_vars全球环境。你可以让他们针对性的,独特的,当你有超过1。

I think, in the main, you aren't adding unnecessary env_vars to the global environment. You can keep them targetted and unique when you have more than 1.

问候,

理查德。

这篇关于从Windows服务访问环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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