C# 访问与设置Windows环境变量

来源:互联网 发布:拼多多比淘宝好做吗 编辑:程序博客网 时间:2024/05/17 22:58
环境变量的类型或位置
枚举:EnvironmentVariableTarget
Process 环境变量存储在与当前进程关联的环境块中,或者从其中检索。User      环境变量存储在 Windows 操作系统注册表的 HKEY_CURRENT_USER\Environment 项中,
      或从其中检索。
Machine 环境变量存储在 Windows 操作系统注册表的
 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment
 项中,或从其中检索。
wwww
User环境变量
eeee
Machine环境变量
aaaa

.NET操作Windows环境变量
静态类:System.Environment
说明:Environment类提供有关当前环境和平台的信息以及操作它们的方法。无法继承此类。使用 Environment类可检索信息,如命令行参数、退出代码、环境变量设置、调用堆栈的内容、自上次系统启动以来的时间,以及公共语言运行库的版本等。
属性:
摘要:获取该进程的命令行。
public static string CommandLine { get; }
摘要:获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。
public static string CurrentDirectory { get; set; }
摘要:获取或设置进程的退出代码。
public static int ExitCode { get; set; }
摘要:获取一个值,该值指示是否公共语言运行库正在关闭或者当前的应用程序域正在卸载。
public static bool HasShutdownStarted { get; }
摘要:获取此本地计算机的 NetBIOS 名称。
public static string MachineName { get; }
摘要:获取为此环境定义的换行字符串。“\r\n”用于非 Unix 平台或“\n”用于 Unix 平台。
public static string NewLine { get; }
摘要:获取包含当前平台标识符和版本号的 System.OperatingSystem 对象。
public static OperatingSystem OSVersion { get; }
摘要:获取当前计算机上的处理器数。
public static int ProcessorCount { get; }
摘要:获取当前的堆栈跟踪信息。
public static string StackTrace { get; }
摘要:获取系统目录的完全限定路径。
public static string SystemDirectory { get; }
摘要:获取系统启动后经过的毫秒数。
public static int TickCount { get; }
摘要:获取与当前用户关联的网络域名。
public static string UserDomainName { get; }
摘要:获取一个值,用以指示当前进程是否在用户交互模式中运行。
public static bool UserInteractive { get; }
摘要:获取启动当前线程的人的用户名。
public static string UserName { get; }
摘要:获取一个System.Version对象,该对象描述公共语言运行库的主版本、次版本、内部版本和修订号。
public static Version Version { get; }
摘要:获取映射到进程上下文的物理内存量。
public static long WorkingSet { get; }
方法:
摘要:终止此进程并为基础操作系统提供指定的退出代码。
public static void Exit(int exitCode);
摘要:将嵌入到指定字符串中的每个环境变量名称替换为该变量的值的等效字符串,然后返回结果字符串。
public static string ExpandEnvironmentVariables(string name);
摘要:终止进程但不执行任何活动 try-finally 块或终结器。
public static void FailFast(string message);
摘要:返回包含当前进程的命令行参数的字符串数组。
public static string[] GetCommandLineArgs();
摘要:从当前进程检索环境变量的值。
public static string GetEnvironmentVariable(string variable);
摘要:从当前进程或者从当前用户或本地计算机的 Windows 操作系统注册表项检索环境变量的值。
public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target);
摘要:从当前进程检索所有环境变量名及其值。
public static IDictionary GetEnvironmentVariables();
摘要:从当前进程或者从当前用户或本地计算机的 Windows 操作系统注册表项检索所有环境变量名及其值。
public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target);
摘要:获取指向由指定枚举标识的系统特殊文件夹的路径。
public static string GetFolderPath(Environment.SpecialFolder folder);
摘要:返回包含当前计算机中的逻辑驱动器名称的字符串数组。
public static string[] GetLogicalDrives();
摘要:创建、修改或删除当前进程中存储的环境变量。
public static void SetEnvironmentVariable(string variable, string value);
摘要:创建、修改或删除当前进程中或者为当前用户或本地计算机保留的 Windows 操作系统注册表项中存储的环境变量。
public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target);
转自http://blog.sina.com.cn/s/blog_48a45b950100gmuf.html

以前实现系统环境变量设置时是要在电脑属性--高级--环境变量设置,实现方式主要有2种,

  1. 修改注册表,添加环境变量
  2. 调用系统Kernel32.DLL函数,设置环境变量

 

 

注册表方式,是要修改注册表的位置是[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]

代码我已经封装,注意要引入命名空间

using Microsoft.Win32;using System.Runtime.InteropServices;

如下:

class SysEnvironment{    /// <summary>    /// 获取系统环境变量    /// </summary>    /// <param name="name"></param>    /// <returns></returns>    public static string GetSysEnvironmentByName(string name)    {        string result = string.Empty;        try        {            result = OpenSysEnvironment().GetValue(name).ToString();//读取        }        catch (Exception)        {            return string.Empty;        }        return result;    }    /// <summary>    /// 打开系统环境变量注册表    /// </summary>    /// <returns>RegistryKey</returns>    private static 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;    }    /// <summary>    /// 设置系统环境变量    /// </summary>    /// <param name="name">变量名</param>    /// <param name="strValue">值</param>    public static void SetSysEnvironment(string name, string strValue)    {        OpenSysEnvironment().SetValue(name, strValue);    }    /// <summary>    /// 检测系统环境变量是否存在    /// </summary>    /// <param name="name"></param>    /// <returns></returns>    public bool CheckSysEnvironmentExist(string name)    {        if (!string.IsNullOrEmpty(GetSysEnvironmentByName(name)))            return true;        else            return false;    }    /// <summary>    /// 添加到PATH环境变量(会检测路径是否存在,存在就不重复)    /// </summary>    /// <param name="strPath"></param>    public static 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 static 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 static 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 + ";" );               }    }}
 
 
Kernel32.DLL内有SetEnvironmentVariable函数用于设置系统环境变量
C#调用要用DllImport,代码封装如下:
class SetSysEnvironmentVariable    {        [DllImport("Kernel32.DLL ", SetLastError = true)]        public static extern bool SetEnvironmentVariable(string lpName, string lpValue);        public static void SetPath(string pathValue)        {            string pathlist;            pathlist = SysEnvironment.GetSysEnvironmentByName("PATH");            string[] list = pathlist.Split(';');            bool isPathExist = false;            foreach (string item in list)            {                if (item == pathValue)                    isPathExist = true;            }            if (!isPathExist)            {                SetEnvironmentVariable("PATH", pathlist + pathValue+";");                           }        }    }


0 0
原创粉丝点击