Open delphidabbler opened 2 years ago
This is not as easy as it seems. There is no official documentation I can find that specifies the valid characters that can be used in an environment variable name.
The only thing I can find by Microsoft says you can't use an equal sign in a name. They also specify size limits.
There's some useful info on Stack Overflow.
Having researched this I think some tests are required.
I've tried all punctuation except =
plus spaces and found that they work.
In fact this documentation by Microsoft does actually say:
The name of an environment variable cannot include an equal sign (=).
It seems that it's true and all other punctuation, letters, numbers and spaces are valid.
That makes the proposed validation routine simple: we just need to check for a =
equal character in any position other than the first position.
Tests show that setting empty values is permitted, so there doesn't need to be anything after the equals sign.
Further test show that empty names are not able to be added to environment variables (the Window API SetEnvironmentVariable
returns an error in this case), so we won't allow it. Note, though, that the process' environment block does contain some variables with no name, e.g. =::=::\
& =C:=C:\Windows\system32
.
So test seems to resolve to:
var EqPos := Pos('=', EnvVar);
if EqPos = 0 then
// error - no equals sign
else if EqPos = 1 then
// error - no name
else
// success
Which resolves to:
begin
Result := Pos('=', Name) > 1;
end;
Also need to consider max length of env vars of 32,767.
Some code in the unit validated an environment variable. This functionality really belongs in
TPJEnvironmentVar
.