- 写注册表方式:
下面是C# 代码,向注册表写入相应的值,来修改环境变量:
private void WriteMainJavaPath2Reg(string strJAVAHome)
{
RegistryKey key = Registry.LocalMachine;
RegistryKey software = null;
//HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
software = key.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",true);
string strPath = software.GetValue("Path").ToString();
bool bTemp = strPath.EndsWith(";");//从字符串的最后位置开始查找是否有"这个符号
if (bTemp)
{
strPath = strPath + strJAVAHome + "\\jre\\bin\\";
}
else
{
strPath = strPath + ";" + strJAVAHome + "\\jre\\bin\\";
}
software.SetValue("Path", strPath, RegistryValueKind.ExpandString);
RegistryKey local_USER = Registry.CurrentUser;
RegistryKey user_ev = null;
user_ev = local_USER.OpenSubKey("Environment", true);
if (user_ev == null)
{
user_ev = local_USER.CreateSubKey("Environment");
user_ev.SetValue("PATH", strJAVAHome + "\\jre\\bin\\", RegistryValueKind.ExpandString);
}
else
{
string[] strEnvironmentNames = user_ev.GetValueNames();
string strTemp = "";
bool exists = ((System.Collections.IList)strEnvironmentNames).Contains("Path");
if (exists)
{
strTemp = user_ev.GetValue("PATH").ToString();
}
bTemp = strTemp.EndsWith(";");
if (bTemp)
{
strTemp = strTemp + strJAVAHome + "\\jre\\bin\\";
}
else
{
if(strTemp.Length > 0)
{
strTemp = strTemp + ";" + strJAVAHome + "\\jre\\bin\\";
}
else
{
strTemp = strTemp + strJAVAHome + "\\jre\\bin\\";
}
}
user_ev.SetValue("Path", strTemp, RegistryValueKind.ExpandString);
}
}
亲测,写注册表的方式在win10是不用重启电脑,修改后马上就可以使用,不过在win7,需要重启电脑,或者是打开windows 环境变量的窗口,点击一下确认,才可以使用。
其实,以上两种方式,都是写注册表的方式,因为set path,是当前工作环境临时有效。而后是无效的。
解决此问题的方法是: 新建一个windows 的c++ 程序,控制台的就好。
以下是此程序的全部代码,拿走不谢。
#include <windows.h>
int main()
{
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)TEXT("Environment"));
return 0;
}
先写入环境变量的注册表,然后管理员运行此程序编译后的exe,那么环境变量就是立即生效了。上面这个程序的意思是,向所有windows桌面程序,发送环境变量发生改变的消息。
还有一种方法,可以直接就修改了环境变量,而不用另外写程序发送 WM_SETTINGCHANGE 消息。
欲知详情,请听下回讲解。关注我的博客哟,www.qq249191508.com