要透過 C# 存取 Windows 環境變數,要了解下述函式
EnvironmentVariableTarget
環境變數範圍
- Process:目前 Process
- User:儲存在 HKEY_CURRENT_USER\Environment
- Machine:儲存在 HKEY_CURRENT_USER\Environment
把環境變數存放在 Process 的話,該 Process 結束後環境變數也就消失囉
Environment.SetEnvironmentVariable
- 環境變數不存在:新增
- 環境變數存在:修改
- null (該範例使用)
- String.Empty
- U+0000
刪除時假如該環境變數不存在,不會拋錯誤
簡易範例
WinForms 簡易範例來對環境變數進行 CRUD
using System.Collections;
namespace EnvVarSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dgvSearch.AutoGenerateColumns = false;
cboSearch.DataSource = Enum.GetNames(typeof(EnvironmentVariableTarget));
cboEnvironmentVariableTarget.DataSource = Enum.GetNames(typeof(EnvironmentVariableTarget));
}
private void cboSearch_SelectionChangeCommitted(object sender, EventArgs e)
{
var (_, _, target) = GetValue();
var source = new List<Source>();
IDictionary vars = Environment.GetEnvironmentVariables(target);
foreach (DictionaryEntry entry in vars)
source.Add(new Source() { EnvVar = entry.Key.ToString(), Value = entry.Value.ToString() });
dgvSearch.DataSource = source;
}
private void btnAddOrModify_Click(object sender, EventArgs e)
{
var input = GetValue();
Environment.SetEnvironmentVariable(input.EnvVar, input.Value, input.Target);
}
private void btnDelete_Click(object sender, EventArgs e)
{
var (EvnVar, _, target) = GetValue();
Environment.SetEnvironmentVariable(EvnVar, null, target);
}
private (string EnvVar, string Value, EnvironmentVariableTarget Target) GetValue()
{
string item = cboEnvironmentVariableTarget.SelectedItem.ToString();
if (Enum.TryParse(item, out EnvironmentVariableTarget target) == false)
throw new NotSupportedException(nameof(item));
return (
txtEnvVar.Text.Trim(),
txtValue.Text.Trim(),
target);
}
private void dgvSearch_SelectionChanged(object sender, EventArgs e)
{
if (dgvSearch.CurrentRow == null)
return;
cboEnvironmentVariableTarget.SelectedIndex = cboEnvironmentVariableTarget.FindStringExact(cboSearch.SelectedItem.ToString());
txtEnvVar.Text = dgvSearch.CurrentRow.Cells[ColEnvVar.Index].Value?.ToString();
txtValue.Text = dgvSearch.CurrentRow.Cells[ColValue.Index].Value?.ToString();
}
private class Source
{
public string EnvVar { get; set; }
public string Value { get; set; }
}
}
}
GetEnvironmentVariables() 和 SetEnvironmentVariable() 沒有指定 EnvironmentVariableTarget 的多載,其 EnvironmentVariableTarget 為 Process 喔
Windows OS GUI 操作
在 Windows OS 的 [系統內容] => 進階 => 環境變數內,可以直接編修 User 和 Machine 的環境變數
沒有留言:
張貼留言