Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 views
in Technique[技术] by (71.8m points)

c# - Accessing Environment Variables from Windows Services

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.

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

Any idea why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

It is done via the registry.

Say the key to your service is ...

HKLMSYSTEMCurrentControlSetServicesYourService

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.

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 ...

HKLMSYSTEMCurrentControlSetServicesYourServiceParameters

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.

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.

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.

Regards,

Richard.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...