using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
namespace ManageTools
{
class SysEnvironment
{
///
/// 获取系统环境变量
///
///
///
public string GetSysEnvironmentByName(string name)
{
string result = string.Empty;
try
{
result = OpenSysEnvironment().GetValue(name).ToString();//读取
}
catch (Exception)
{
return string.Empty;
}
return result;
}
///
/// 打开系统环境变量注册表
///
/// RegistryKey
private RegistryKey OpenSysEnvironment()
{
RegistryKey regLocalMachine = Registry.LocalMachine;
RegistryKey regSYSTEM = regLocalMachine.OpenSubKey("SYSTEM", true);//打开HKEY_LOCAL_MACHINE下的SYSTEM
RegistryKey regControlSet001 = regSYSTEM.OpenSubKey("ControlSet001", true);//打开ControlSet001
RegistryKey regControl = regControlSet001.OpenSubKey("Control", true);//打开Control
RegistryKey regManager = regControl.OpenSubKey("Session Manager", true);//打开Control
RegistryKey regEnvironment = regManager.OpenSubKey("Environment", true);
return regEnvironment;
}
///
/// 设置系统环境变量
///
/// 变量名
/// 值
public void SetSysEnvironment(string name, string strValue)
{
OpenSysEnvironment().SetValue(name, strValue);
}
///
/// 检测系统环境变量是否存在
///
///
///
public bool CheckSysEnvironmentExist(string name)
{
if (!string.IsNullOrEmpty(GetSysEnvironmentByName(name)))
return true;
else
return false;
}
///
/// 添加到PATH环境变量(会检测路径是否存在,存在就不重复)
///
///
public void SetPathAfter(string strHome)
{
string pathlist;
pathlist = GetSysEnvironmentByName("PATH");
//检测是否以;结尾
if (pathlist.Substring(pathlist.Length - 1, 1) != ";")
{
SetSysEnvironment("PATH", pathlist + ";");
pathlist = GetSysEnvironmentByName("PATH");
}
string[] list = pathlist.Split(';');
bool isPathExist = false;
foreach (string item in list)
{
if (item == strHome)
isPathExist = true;
}
if (!isPathExist)
{
SetSysEnvironment("PATH", pathlist + strHome + ";");
}
}
public void SetPathBefore(string strHome)
{
string pathlist;
pathlist = GetSysEnvironmentByName("PATH");
string[] list = pathlist.Split(';');
bool isPathExist = false;
foreach (string item in list)
{
if (item == strHome)
isPathExist = true;
}
if (!isPathExist)
{
SetSysEnvironment("PATH", strHome + ";" + pathlist);
}
}
public void SetPath(string strHome)
{
string pathlist;
pathlist = GetSysEnvironmentByName("PATH");
string[] list = pathlist.Split(';');
bool isPathExist = false;
foreach (string item in list)
{
if (item == strHome)
isPathExist = true;
}
if (!isPathExist)
{
SetSysEnvironment("PATH", pathlist + strHome + ";");
}
}
}
}