原文:C# 实现设置系统环境变量设置

以前实现系统环境变量设置时是要在电脑属性--高级--环境变量设置,实现方式主要有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+";");

}

}
}

 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

C# 实现设置系统环境变量设置的更多相关文章

  1. 使用VBScript实现设置系统环境变量的小程序

    本人有点桌面洁癖,桌面上只放很少的东西,很多软件都用快捷键调出.最近频繁用到一个软件,我又不想放个快捷方式在桌面,也不想附到开始菜单,于是乎想将其所在目录附加到系统环境变量Path上,以后直接在运行中 ...

  2. Visual Studio 2012系统环境变量设置(命令行)

    方法1.运行脚本vsvars32.bat:D:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\vsvars32.bat ...

  3. [Java] JDK 系统环境变量设置 bat

    @echo off set regpath=HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environmen ...

  4. 下载JDK和Jmeter并设置系统环境变量

    一.JDK下载并设置系统环境变量 1.JDK官网下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html 点左边的 ...

  5. 通过bat设置系统环境变量

    在软件运行过程中,可能需要配置计算机的环境变量,在这里分为两种情况: 一:增加或修改环境变量只在当前软件环境中使用 如我们设置Java的环境变量: set CLASSPATH=%CLASSPATH%; ...

  6. C# 设置系统环境变量

    using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; ...

  7. linux设置系统环境变量的天坑

    在设置系统环境变量,也就是 .bash_profile 或者 /etc/proflie 或者 .bashrc 中把path写错或者是把设置系统环境变量的格式写错! 会 导致 系统无法进入.登录无限循环 ...

  8. DOS永久设置系统环境变量-WMIC

    wmic Windows Management Instrumentation Command-line(Windows管理规范命令行) WMIC扩展WMI(Windows Management In ...

  9. [置顶] getenv、setenv函数(获取和设置系统环境变量) 与 环境变量

    1.getenv() 函数名: getenv 功 能: 从环境中取字符串,获取环境变量的值 头文件: stdlib.h 用 法:char *getenv(char *envvar); 函数说明:get ...

随机推荐

  1. C# 读取IE缓存文件(2)

    private void button1_Click(object sender, EventArgs e) { , nBufSize; IntPtr buf; INTERNET_CACHE_ENTR ...

  2. Cygwin编译自己定义OpenCV库报错:opencv_contrib: LOCAL_SRC_FILES points to a missing file

    今天受命帮师弟调个OpenCV4Android 识别银行卡的程序,版本号为OpenCV4Android2.4.9,使用方式为前文介绍的第一种方式,即通过jni调用opencv.如杂家前文所述,配套的N ...

  3. Unity该插件NGUI得知(9)—— Tween并转换成世界坐标系的大小NGUI尺寸

    在游戏中,还有一种比较常见的动画,这是进球后产生,分数将被显示在游戏,而快速移动,使其失去位置加入.就打算使用NGUI的Tween来制作这样的分数动画效果. 依据 Unity插件之NGUI学习(2), ...

  4. 原生js判断css3动画过度(transition)结束 transitionend事件 以及关键帧keyframes动画结束(animation)回调函数 animationEnd 以及 css 过渡 transition无效

      上图的 demo 主要讲的 是 css transition的过渡回调函数transitionend事件: css3 的时代,css3--动画 一切皆有可能: 传统的js 可以通过回调函数判断动画 ...

  5. 照片教你eclipse通过使用gradle 打包Android

    gradle其他优点不说,在android当应用程序公布.假设你要算一些渠道,gradle 在节目包装散装优势:下面给大家介绍的图形 按eclipse当出口 选择Android:例如下面的附图 一步一 ...

  6. HDOJ 4745 Two Rabbits DP

    Two Rabbits Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65535/65535 K (Java/Others) Tot ...

  7. JavaScript变量作用域和内存问题(二)

    执行环境是js中特别重要的概念,是指变量或者函数可以访问其他数据,定义自己的行为.每个执行环境都有一个与之相对应的变量对象,执行环境中定义的所有变量和函数都保存在这个变量中,我们看不到这个变量,但是后 ...

  8. Codeforces Beta Round #3 A. Shortest path of the king

    标题效果: 鉴于国际棋盘两点,寻求同意的操作,是什么操作的最小数量,在操作过程中输出. 解题思路: 水题一个,见代码. 以下是代码: #include <set> #include < ...

  9. css3 3d旋转动画

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  10. 《R实战》读书笔记三

    第二章  创建数据集 本章概要 1探索R数据结构 2使用数据编辑器 3数据导入 4数据集标注 本章所介绍内容概括例如以下. 两个方面的内容. 方面一:R数据结构 方面二:进入数据或者导入数据到数据结构 ...