C# 设置系统环境变量
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms; namespace WindowsForms设置系统变量
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{ //var str = SysEnvironment.GetSysEnvironmentByName("Path"); //系统变量 Path
// SysEnvironment.SetSysEnvironment("Path", "0");
//HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment 下的Path值
SysEnvironment.SetPathAfter(@"C:\mysql\bin");
MessageBox.Show("完成!" + @"C:\mysql\bin;");
var str = SysEnvironment.GetSysEnvironmentByName("Path"); //系统变量 Path
string[] temp = str.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = ; i < temp.Length; i++)
{
textBox1.Text += temp[i] + "\r\n";
}
} private void button2_Click(object sender, EventArgs e)
{
////RunCmd(@"C:\Windows\System32\","ipconfig");
//System.Diagnostics.Process.Start(@"C:\Windows\System32\cmd.exe");
//textBox2.Text += Cmd(@"CD C:\mysql mysqld --defaults-file=my.ini --initialize-insecure"); }
///<summary>
/// cmd命令执行,在cmd上可以执行的语句,直接传到这里,调用grads画图实例如下:
/// Cmd("C:/OpenGrADS/Contents/Cygwin/Versions/2.0.1.oga.1/i686/grads.exe -lbcx 'D:/data_wrfchem/gs/d01_hour_pm25.gs D:/data_wrfchem 2016-04-18 d01'");
/// Cmd("grads启动程序exe路径 -lbcx 'gs脚本文件 参数1 参数2 参数3'");
/// </summary>
/// <param name="c">执行语句</param>
public string Cmd(string c)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
process.StandardInput.WriteLine(c);
process.StandardInput.AutoFlush = true;
process.StandardInput.WriteLine("exit");
StreamReader reader = process.StandardOutput;//截取输出流
//string output = reader.ReadLine();//每次读取一行
//while (!reader.EndOfStream)
//{
// // PrintThrendInfo(output);
// output = reader.ReadLine();
//}
string output = reader.ReadToEnd();//每次读取一行
process.WaitForExit(); return output;
}
} public static class SysEnvironment
{ #region --获取注册表中的环境变量 /// <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);
}
#endregion /// <summary>
/// 检测系统环境变量是否存在
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static 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"); bool isPathExist = false;
if (pathlist.Length > )
{
//检测是否以;结尾
if (pathlist.Substring(pathlist.Length - , ) != ";") //截取最后一个字符,判断这个字符不等于;号,
{
SetSysEnvironment("PATH", pathlist + ";");
pathlist = GetSysEnvironmentByName("PATH");
}
string[] list = pathlist.Split(';');//以;切割 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 + ";"); } }
} }
C# 设置系统环境变量的更多相关文章
- 使用VBScript实现设置系统环境变量的小程序
本人有点桌面洁癖,桌面上只放很少的东西,很多软件都用快捷键调出.最近频繁用到一个软件,我又不想放个快捷方式在桌面,也不想附到开始菜单,于是乎想将其所在目录附加到系统环境变量Path上,以后直接在运行中 ...
- C# 实现设置系统环境变量设置
原文:C# 实现设置系统环境变量设置 以前实现系统环境变量设置时是要在电脑属性--高级--环境变量设置,实现方式主要有2种, 修改注册表,添加环境变量 调用系统Kernel32.DLL函数,设置环境变 ...
- 下载JDK和Jmeter并设置系统环境变量
一.JDK下载并设置系统环境变量 1.JDK官网下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html 点左边的 ...
- 通过bat设置系统环境变量
在软件运行过程中,可能需要配置计算机的环境变量,在这里分为两种情况: 一:增加或修改环境变量只在当前软件环境中使用 如我们设置Java的环境变量: set CLASSPATH=%CLASSPATH%; ...
- linux设置系统环境变量的天坑
在设置系统环境变量,也就是 .bash_profile 或者 /etc/proflie 或者 .bashrc 中把path写错或者是把设置系统环境变量的格式写错! 会 导致 系统无法进入.登录无限循环 ...
- DOS永久设置系统环境变量-WMIC
wmic Windows Management Instrumentation Command-line(Windows管理规范命令行) WMIC扩展WMI(Windows Management In ...
- [置顶]
getenv、setenv函数(获取和设置系统环境变量) 与 环境变量
1.getenv() 函数名: getenv 功 能: 从环境中取字符串,获取环境变量的值 头文件: stdlib.h 用 法:char *getenv(char *envvar); 函数说明:get ...
- bat脚本设置系统环境变量即时生效
关于bat的资料多但零碎,记录一下. 1.设置环境变量即时生效:通过重启explorer来实现即时生效(亲测有效) @echo off set curPath=%cd% wmic ENVIRONMEN ...
- Visual Studio 2012系统环境变量设置(命令行)
方法1.运行脚本vsvars32.bat:D:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\vsvars32.bat ...
随机推荐
- java抛出异常后,后续代码是否可继续执行
参考:https://www.cnblogs.com/wangyingli/p/5912269.html 仅此可正常执行异常后内容 try{ throw new Exception("参数越 ...
- Remove '@override' annotation解决办法
最近刚刚配置了新机器,将原来的代码放在eclipse上执行,总会出现Remove '@override' annotation,如果要一个个手动删除相当麻烦,最后在网上找了一下原因原来是编译器版本的问 ...
- mac终端命令加密压缩文件为zip包
mac终端命令加密压缩文件为zip包,命令如下: zip -e ~/desktop/a.zip b.doc c.txt d.sql 注释:a.zip为加密后的文件 b.doc c.txt d.sql为 ...
- 分析函数Ratio_to_report使用
分析函数Ratio_to_report( ) over()使用说明 表中需要计算单项占比:比如单项在部门占比多少,单项在公司占比多少.特别是在财务单项计算,部门个人薪水计算上. Ratio_to_re ...
- 【192】PowerShell 相关知识
默写说明: 查询别名所指的真实cmdlet命令. Get-Alias -name ls 查看可用的别名,可以通过 “ls alias:” 或者 “Get-Alias”. 查看所有以Remove打头的c ...
- bzoj 4584: [Apio2016]赛艇【dp】
参考:https://www.cnblogs.com/lcf-2000/p/6809085.html 设f[i][j][k]为第i个学校派出的赛艇数量在区间j内,并且区间j内共有k个学校的方案数 把数 ...
- JS开发备忘笔记-- Javascript中document.execCommand()的用法
document.execCommand()方法处理Html数据时常用语法格式如下:document.execCommand(sCommand[,交互方式, 动态参数]) 其中:sCommand为指令 ...
- maven-将依赖的 jar包一起打包到项目 jar 包中
前言: 有时候在项目开发中,需要很多依赖的 jar 包,其中依赖的 jar 包也会依赖其他的 jar 包,导致jar 包的管理很容易不全,以下有两种方法可以规避这个问题. 一.在pom.xml 文件中 ...
- Allure对单测结果以及robotframework结果的处理
Allure对单测结果以及robotframework结果的处理 Allure只能针对pytest的单测结果生成相应的报告: 如果需要对unittest的测试框架结果进行展示,可以使用pytest执行 ...
- linux unzip和zip
注:*压缩成限.zip格式文件 常用解压缩: [root@mysql test]# unzip -o test.zip -d tmp/ 将压缩文件test.zip在指定目录tmp下解压缩,如果已有相同 ...