原文: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#软件开发实例.个人定制自己的屏幕抓图工具(八)加入了截图功能键盘

    章文件夹 (一)功能概览 (二)创建项目.注冊热键.显示截图主窗体 (三)托盘图标及菜单的实现 (四)基本截图功能实现 (五)针对拖拽时闪烁卡顿现象的优化 (六)加入配置管理功能 (七)加入放大镜的功 ...

  2. Hibernate在关于一对多,多对一双向关联映射

    [Hibernate]之关于一对多,多对一双向关联映射 因为一对多.和多对一的双向关联映射基本上一样,所以这里就一起写下来! Annotations配置 @Entity @Table(name=&qu ...

  3. Android学习路径(七)建立Action Bar

    在action bar最今本的形式中,它只在左边展示了activity的标题以及应用的icon. 即使在这样的简单的形式中,它也不过告诉用户如今在应用的哪个activity中,同一时候为你的应用保持一 ...

  4. SWFUpload多文件上传 文件数限制 setStats()

    使用swfupload仿公平图片上传 SWFUpload它是基于flash与javascript的client文件上传组件. handlers.js文件 完毕文件入列队(fileQueued) → 完 ...

  5. 初步boost之pool图书馆学习笔记

    pool 内存池概述 通常我们习惯直接使用new.malloc等API申请分配内存,这样做的缺点在于:因为所申请内存块的大小不定.当频繁使用时会造成大量的内存碎片并进而减少性能. 内存池则是在真正使用 ...

  6. Team Foundation Server 2015使用教程--团队项目创建

  7. HTML5学习笔记简明版(10):过时的元素和属性

    被遗弃的元素(Element) 这个小节里列出的元素在HTML5里将不再使用,现有文档升级到 HTML5的话能够使用一些替代方案.比如parser section 能够处理isindex 元素的功能. ...

  8. ZOJ3605-Find the Marble(可能性DP)

    Find the Marble Time Limit: 2 Seconds      Memory Limit: 65536 KB Alice and Bob are playing a game. ...

  9. 控件注册 - 利用资源文件将dll、ocx打包进exe文件(C#版)

    原文:控件注册 - 利用资源文件将dll.ocx打包进exe文件(C#版) 很多时候自定义或者引用控件都需要注册才能使用,但是如何使要注册的dll或ocx打包到exe中,使用户下载以后看到的只是一个e ...

  10. Class loader:static

    package classloader; public class ClassLoaderDisplayDemo { public static void main(String[] args) { ...