Question

I'm trying to load managed and native dll into my C# application. I want to set the PATH environment variable, so the application can find the dlls to be loaded. In C++ that's easy, but how can I do that in a C# project? (By the way I'm using VS2012, .NET, WPF)

Was it helpful?

Solution

Use Environment.SetEnvironmentVariable().

string currentPath = Environment.GetEnvironmentVariable("path");
Environment.SetEnvironmentVariable("path",currentPath + ";c:\path_to_libraries");

Keep in mind that this will only be in scope for the current process. If you want to set a persistent environment variable (user or machine scope) use the Environment.SetEnvironmentVariable(string, string, EnvironmentVariableTarget) overload. See here for that reference.

OTHER TIPS

Be careful with this thing. I would explicitly set the target e.g. System.Environment.SetEnvironmentVariable("windir", System.Environment.GetEnvironmentVariable("SystemRoot"), EnvironmentVariableTarget.User);

When I did not set the target, very odd things happened to my Windows session requiring me to either logoff and login or even reboot. So unless this change is really to be at the machine or process level, do not assume happy results with the default

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top