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 + ";"); } }
} }

最新文章

  1. 小谈Scrum敏捷开发流程
  2. php编译安装报错:make: *** [sapi/cli/php] Error 1 解决办法
  3. ECMAScript6 面向对象 时钟效果
  4. ycm添加自定义补全路径
  5. js 读写cookie。不同路径会储存各自的cookie。而 在v.net环境下读写是在 / 根目录。
  6. 程序员谈学习:我为什么要学习Linux?
  7. 理解newid()和newsequentialid()
  8. 打包静默安装参数(nsis,msi,InstallShield,InnoSetup)[转]
  9. phpStorm 各种快捷键
  10. Android Studio代码自己主动提示无效(not available in Power Save mode)
  11. [leetcode-628-Maximum Product of Three Numbers]
  12. Linux命令用法
  13. linux下磁盘占用达到100%了,找不到哪些大文件耗尽了磁盘
  14. 计算机网络网络层的IP地址划分及子码
  15. TZOJ 2569 Wooden Fence(凸包求周长)
  16. webserver nginx / https / upstream
  17. mysql distinct 用法详解及优化
  18. dos脚本2
  19. C++生成斐波拉其数列
  20. angular.element 动态添加和删除元素

热门文章

  1. sphinx索引部分源码续——过程:连接到CSphSource对应的sql数据源,通过fetch row取其中一行,然后解析出field,分词,获得wordhit,最后再加入到CSphSource的Hits里
  2. AutoIT: WinActivate可以把要操作的窗口提前。
  3. 洛谷 P1072 Hankson 的趣味题 —— 质因数分解
  4. 洛谷P4136 谁能赢呢?——博弈
  5. VS2013Xml文件节点导航插件开发
  6. bootstrap-table 行合并和列合并,以及固定列宽度等问题
  7. hibernate映射文件set key one-to-many
  8. DateTime?转化为DateTime,int? 转 int
  9. 让CentOS启动后直接进入命令行模式(转载)
  10. bzoj P1979 华容道【bfs+spfa】