This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
Environment.Unix.cs
101 lines (89 loc) · 3.2 KB
/
Environment.Unix.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System
{
public static partial class Environment
{
private static readonly unsafe Lazy<Dictionary<string, string>> s_environ = new Lazy<Dictionary<string, string>>(() =>
{
// We cache on Unix as using the block isn't thread safe
return GetRawEnvironmentVariables();
});
private static string GetEnvironmentVariableCore(string variable)
{
// Ensure variable doesn't include a null char
int nullEnd = variable.IndexOf('\0');
if (nullEnd != -1)
{
variable = variable.Substring(0, nullEnd);
}
// Get the value of the variable
lock (s_environ)
{
string value;
return s_environ.Value.TryGetValue(variable, out value) ? value : null;
}
}
private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
{
return target == EnvironmentVariableTarget.Process ?
GetEnvironmentVariableCore(variable) :
null;
}
private static IDictionary GetEnvironmentVariablesCore()
{
lock (s_environ)
{
return new Dictionary<string, string>(s_environ.Value);
}
}
private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
{
return target == EnvironmentVariableTarget.Process ?
GetEnvironmentVariablesCore() :
new Dictionary<string, string>();
}
private static void SetEnvironmentVariableCore(string variable, string value)
{
int nullEnd;
// Ensure variable doesn't include a null char
nullEnd = variable.IndexOf('\0');
if (nullEnd != -1)
{
variable = variable.Substring(0, nullEnd);
}
// Ensure value doesn't include a null char
if (value != null)
{
nullEnd = value.IndexOf('\0');
if (nullEnd != -1)
{
value = value.Substring(0, nullEnd);
}
}
lock (s_environ)
{
// Remove the entry if the value is null, otherwise add/overwrite it
if (value == null)
{
s_environ.Value.Remove(variable);
}
else
{
s_environ.Value[variable] = value;
}
}
}
private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
{
if (target == EnvironmentVariableTarget.Process)
{
SetEnvironmentVariableCore(variable, value);
}
// other targets ignored
}
}
}