简体   繁体   English

如何为C#调试设置环境变量

[英]How to set environment variable for C# debugging

I'm trying to load managed and native dll into my C# application. 我正在尝试将托管和本机dll加载到C#应用程序中。 I want to set the PATH environment variable, so the application can find the dlls to be loaded. 我想设置PATH环境变量,以便应用程序可以找到要加载的dll。 In C++ that's easy, but how can I do that in a C# project? 在C ++中,这很容易,但是如何在C#项目中做到这一点呢? (By the way I'm using VS2012, .NET, WPF) (通过我使用VS2012,.NET,WPF的方式)

Use Environment.SetEnvironmentVariable() . 使用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. 如果要设置持久性环境变量(用户或计算机范围),请使用Environment.SetEnvironmentVariable(string, string, EnvironmentVariableTarget)重载。 See here for that reference. 请参阅此处以获取该参考。

Be careful with this thing. 小心这件事。 I would explicitly set the target eg System.Environment.SetEnvironmentVariable("windir", System.Environment.GetEnvironmentVariable("SystemRoot"), EnvironmentVariableTarget.User); 我会明确设置目标,例如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. 当我没有设置目标时,Windows会话发生了非常奇怪的事情,要求我注销并重新登录甚至重新启动。 So unless this change is really to be at the machine or process level, do not assume happy results with the default 因此,除非此更改确实要在计算机或过程级别进行,否则不要在默认情况下得出令人满意的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM