c#实现添加和删除Windows系统环境变量
直接上代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddEnvironmentVariable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ProcessCommandLineArguments();
CenterToScreen();
}
private void buttonOK_Click(object sender, EventArgs e)
{
// 检测Ctrl键状态
bool ctrlPressed = (Control.ModifierKeys & Keys.Control) == Keys.Control;
if (ctrlPressed)
{
if (string.IsNullOrEmpty(txtEnvName.Text))
{
MessageBox.Show("名称为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
bool success = EnvironmentVariableHelper.DeleteSystemEnvironmentVariable(txtEnvName.Text);
lblStatus.Text = success ? "删除成功" : "删除失败";
}
else
{
bool success = UpdateEnvironmentVariable(txtEnvName, txtEnvValue);
lblStatus.Text = success ? "更新成功" : "更新失败";
}
}
public void AutoPasteFromClipboard(TextBox textBox)
{
// 判断当前文本框是否为空
if (!string.IsNullOrWhiteSpace(textBox.Text))
return;
try
{
// 安全检查剪贴板内容
if (!Clipboard.ContainsText())
return;
// 获取并验证剪贴板文本
string clipboardText = Clipboard.GetText().Trim();
if (clipboardText.Length == 0 || clipboardText.Length > 256)
return;
// 执行安全赋值
textBox.Invoke((MethodInvoker)delegate
{
textBox.Text = clipboardText;
textBox.SelectionStart = textBox.Text.Length; // 光标定位到末尾
});
}
catch (System.Runtime.InteropServices.COMException)
{
// 处理剪贴板访问冲突
}
catch (Exception ex)
{
// 调试时可取消注释
// System.Diagnostics.Debug.WriteLine($"Clipboard error: {ex.Message}");
}
}
public bool UpdateEnvironmentVariable(TextBox tbKey, TextBox tbValue)
{
// 检查关键值是否为空
if (string.IsNullOrWhiteSpace(tbKey.Text))
{
MessageBox.Show("环境变量名称不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
string key = tbKey.Text.Trim();
string inputValue = tbValue.Text.Trim();
try
{
// 当值输入框为空时的处理逻辑
if (string.IsNullOrEmpty(inputValue))
{
// 获取现有环境变量值
string existingValue = EnvironmentVariableHelper.GetSystemEnvironmentVariable(key);
if (existingValue != null)
{
// 回填已有值到界面
tbValue.Text = existingValue;
return true;
}
else
{
MessageBox.Show($"环境变量 {key} 不存在");
return false;
}
}
else
{
// 尝试追加新值
if (EnvironmentVariableHelper.AppendSystemEnvironmentVariable(key, inputValue))
{
// 获取更新后的完整值
string updatedValue = EnvironmentVariableHelper.GetSystemEnvironmentVariable(key);
tbValue.Text = updatedValue;
return true;
}
return false;
}
}
catch (Exception ex)
{
MessageBox.Show($"操作失败: {ex.Message}");
return false;
}
}
private void ProcessCommandLineArguments()
{
string[] args = Environment.GetCommandLineArgs();
// 在UI线程更新状态
void UpdateStatus(string message)
{
if (lblStatus.InvokeRequired)
{
lblStatus.Invoke(new Action(() => lblStatus.Text = message));
}
else
{
lblStatus.Text = message;
}
}
try
{
if (args.Length < 2)
{
return;
}
string operation = args[1].ToLower();
switch (operation)
{
case "-add":
HandleAddOperation(args, UpdateStatus);
break;
case "-del":
HandleDeleteOperation(args, UpdateStatus);
break;
default:
UpdateStatus($"无效操作命令: {operation}");
break;
}
}
catch (Exception ex)
{
UpdateStatus($"操作异常: {ex.Message}");
}
}
private void HandleAddOperation(string[] args, Action<string> updateStatus)
{
if (args.Length < 4)
{
updateStatus("添加操作参数不完整\n正确格式:-add \"变量名\" \"变量值\"");
return;
}
string varName = args[2];
string varValue = args[3];
if (string.IsNullOrWhiteSpace(varName))
{
updateStatus("错误:环境变量名称不能为空");
return;
}
bool result = EnvironmentVariableHelper.AppendSystemEnvironmentVariable(varName, varValue);
updateStatus(result ?
$"✅ 成功添加系统环境变量:{varName}" :
$"❌ 添加失败:{varName}可能原因:1. 无管理员权限2. 注册表访问被拒绝");
}
private void HandleDeleteOperation(string[] args, Action<string> updateStatus)
{
if (args.Length < 3)
{
updateStatus("删除操作参数不完整正确格式:-del \"变量名\"");
return;
}
string varName = args[2];
if (string.IsNullOrWhiteSpace(varName))
{
updateStatus("错误:环境变量名称不能为空");
return;
}
bool result = EnvironmentVariableHelper.DeleteSystemEnvironmentVariable(varName);
updateStatus(result ?
$"✅ 成功删除系统环境变量:{varName}" :
$"❌ 删除失败:{varName}可能原因:1. 变量不存在2. 无管理员权限");
}
// 如果需要在非UI线程更新控件
private void SafeUpdateTextBox(TextBox box, string value)
{
if (box.InvokeRequired)
{
box.Invoke(new Action(() => box.Text = value));
}
else
{
box.Text = value;
}
}
private void txtEnvName_MouseClick(object sender, MouseEventArgs e)
{
AutoPasteFromClipboard(sender as TextBox);
}
private void txtEnvValue_MouseClick(object sender, MouseEventArgs e)
{
AutoPasteFromClipboard(sender as TextBox);
}
}
}
using Microsoft.Win32;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
public class EnvironmentVariableHelper
{
public static bool AppendSystemEnvironmentVariable(string name, string value)
{
try
{
using (var environmentKey = Registry.LocalMachine.OpenSubKey(
@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
{
if (environmentKey == null) return false;
// 查找实际存在的变量名(不区分大小写)
var existingNames = environmentKey.GetValueNames();
string targetName = existingNames.FirstOrDefault(n =>
string.Equals(n, name, StringComparison.OrdinalIgnoreCase));
// 获取当前原始值(未展开的)
string currentValue = targetName != null ?
environmentKey.GetValue(targetName, null,
RegistryValueOptions.DoNotExpandEnvironmentNames) as string : null;
// 处理不同情况
if (currentValue == null)
{
// 变量不存在,直接创建
environmentKey.SetValue(name, value, RegistryValueKind.ExpandString);
}
else
{
// 分割现有值并检查重复
var values = currentValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (!values.Contains(value, StringComparer.OrdinalIgnoreCase))
{
// 追加新值并保留原始格式
string newValue = $"{currentValue.TrimEnd(';')};{value}";
environmentKey.SetValue(targetName, newValue, RegistryValueKind.ExpandString);
}
else
{
// 值已存在,无需修改
return true;
}
}
// 广播环境变量变更
BroadcastEnvironmentChange();
return true;
}
}
catch (SecurityException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
catch (Exception)
{
return false;
}
}
public static bool DeleteSystemEnvironmentVariable(string name)
{
try
{
using (var environmentKey = Registry.LocalMachine.OpenSubKey(
@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
{
if (environmentKey == null) return false;
// 查找实际存在的变量名(不区分大小写)
var existingNames = environmentKey.GetValueNames();
string targetName = existingNames.FirstOrDefault(n =>
string.Equals(n, name, StringComparison.OrdinalIgnoreCase));
if (targetName != null)
{
// 删除注册表项
environmentKey.DeleteValue(targetName);
// 广播环境变量变更
BroadcastEnvironmentChange();
return true;
}
return false; // 变量不存在
}
}
catch (SecurityException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
catch (Exception)
{
return false;
}
}
public static bool SetSystemEnvironmentVariable(string name, string value)
{
try
{
using (var environmentKey = Registry.LocalMachine.OpenSubKey(
@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
{
if (environmentKey == null) return false;
// 检查变量是否存在(不区分大小写)
var existingNames = environmentKey.GetValueNames();
string targetName = existingNames.FirstOrDefault(n =>
string.Equals(n, name, StringComparison.OrdinalIgnoreCase));
// 获取当前值(未展开的原始值)
string currentValue = targetName != null ?
environmentKey.GetValue(targetName, null,
RegistryValueOptions.DoNotExpandEnvironmentNames) as string : null;
if (currentValue == value)
{
return true; // 值相同无需修改
}
// 设置/更新值(保留原变量名的大小写)
environmentKey.SetValue(targetName ?? name, value, RegistryValueKind.ExpandString);
// 广播环境变量变更
BroadcastEnvironmentChange();
return true;
}
}
catch (SecurityException)
{
// 需要管理员权限
return false;
}
catch (UnauthorizedAccessException)
{
// 权限不足
return false;
}
catch (Exception)
{
// 其他错误(如无效名称等)
return false;
}
}
public static string GetSystemEnvironmentVariable(string name)
{
using (var environmentKey = Registry.LocalMachine.OpenSubKey(
@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"))
{
if (environmentKey == null) return null;
// 查找实际存在的变量名(不区分大小写)
var existingNames = environmentKey.GetValueNames();
string targetName = existingNames.FirstOrDefault(n =>
string.Equals(n, name, StringComparison.OrdinalIgnoreCase));
return targetName != null ?
environmentKey.GetValue(targetName, null,
RegistryValueOptions.DoNotExpandEnvironmentNames) as string : null;
}
}
private static void BroadcastEnvironmentChange()
{
try
{
IntPtr hwndBroadcast = (IntPtr)0xFFFF; // HWND_BROADCAST
uint WM_SETTINGCHANGE = 0x001A;
UIntPtr result;
SendMessageTimeout(
hwndBroadcast,
WM_SETTINGCHANGE,
UIntPtr.Zero,
"Environment",
0x0002, // SMTO_ABORTIFHUNG
5000,
out result);
}
catch
{
// 忽略广播失败(环境变量仍会被记录到注册表)
}
}
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint Msg,
UIntPtr wParam,
string lParam,
uint fuFlags,
uint uTimeout,
out UIntPtr lpdwResult);
}
实现了点击确定按钮添加环境变量,按下Ctrl按钮点击的时候则删除环境变量,也可以用于查看环境变量。