C # set system environment variables

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 = 0; 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 cmd + = .text (@ "the CD C: \ File-MySQL mysqld = --defaults the my.ini --initialize-in the insecure"); 

        } 
        /// <Summary> 
        /// cmd command may be performed on cmd statement directly to where calls grads drawing examples are as follows:
         ///   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 (" exe launcher GrADS path -lbcx' gs script parameter 2 parameter 3 parameter 1 ' ");
         // /  </ Summary> 
        ///  <param name = "c "> executing statements </ 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 = to true ; 
            process.StandardInput.WriteLine ( " Exit " ); 
            the StreamReader Reader = process.StandardOutput; // intercepting the output stream
             // String reader.readLine Output = (); // read each line
             / / the while (! reader.EndOfStream)
             // {
             //     // PrintThrendInfo (Output);
             //     Output = reader.readLine ();
             // } 
            String= reader.ReadToEnd Output (); // read each line of 
            the Process.WaitForExit (); 

            return Output; 
        } 
    } 


    public  static  class SysEnvironment 
    { 


        #region - Get registry environment variables /// <Summary> // / acquisition system environment variables
         /// </ Summary> /// <param name = "name"> </ param> /// <Returns> </ Returns> public static String GetSysEnvironmentByName ( String name) 
        { String Result = String .Empty;
             the 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> 
        /// detection system environment variable exists
         ///  </ Summary> 
        ///  <param name = "name"> </ param> 
        ///  <Returns> </ Returns> 
        public  static  BOOL CheckSysEnvironmentExist ( String name) 
        { 
            iF (! String .IsNullOrEmpty (GetSysEnvironmentByName (name)))
                 return  to true ;
             the else 
                return  to false ; 
        } 

        ///  <Summary> 
        /// to the pATH environment variable (detects path exists, present is not repeated)
         ///  </ Summary>
        /// <param name = "strPath"> </ param> 
        public  static  void SetPathAfter ( String strHome) 
        { 
            String pathlist; 
            pathlist = GetSysEnvironmentByName ( " the PATH " ); 

            BOOL isPathExist = to false ;
             IF (pathlist.Length> . 1 ) 
            { 
                // Detection whether ends with; 
                iF (pathlist.Substring (pathlist.Length - . 1 , . 1 ) =! " ; " ) // taken the last character, the character is determined not equal; number,
                 {
                    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 + + " pathValue); " ); 
            } 
        } 
    } 

    // inner Kernel32.DLL SetEnvironmentVariable function for setting the system environment variables
     // C # calls use DllImport, encapsulated code is as follows: 
    class SetSysEnvironmentVariable 
    { 
        [the DllImport ( " Kernel32.DLL " , the SetLastError = to true ) ]
         public  static  extern  BOOL the SetEnvironmentVariable ( String lpName, String lpValue); 

        public  static  void SetPath ( String 
        { 
            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 + ";");

            }

        }
    }


}

 

Guess you like

Origin www.cnblogs.com/enych/p/11084319.html