public static string ReplaceEnvironmentVariables(string val, bool tolerant)
{
string retVal = null;
if (val != null)
{
// Seperate all pieces that might be env vars.
string[] parts = val.Split('%');
if (parts.Length == 1) {
// No % in the string, couldn't substitute any vars.
retVal = val;
}
else if (parts.Length == 2)
{
string message = "There was one % in the string, couldn't substitute any vars: '" +
val + "'.";
if (tolerant)
{
retVal = val;
}
else
{
throw new LoggingException(message);
}
}
else
{
StringBuilder returnString = new StringBuilder();
// There's no % before the first part.
bool leadingPerc = false;
// For each part (except the last, which can't be),
// see if it's an environment variable.
for (int index = 0; index < (parts.Length - 1); index++)
{
if (leadingPerc)
{
string envValue = Environment.GetEnvironmentVariable(
parts[index].ToUpper());
if (string.IsNullOrEmpty(envValue))
{
string message = "Value '" + val + "' has substring '%" + parts[index] + "%'" +
" which is not an environment variable.";
if (tolerant)
{
_log.Warn(message);
// Put it back in the output string unchanged.
returnString.Append("%"); // % was stripped out by the 'split' call.
returnString.Append(parts[index]);
// This isn't a variable, so it isn't using the next % either.
// So leave leadingPerc set to 'true',
}
else
{
throw new LoggingException(message);
}
}
else
{
returnString.Append(envValue);
// We just used the following %.
leadingPerc = false;
}
}
else
{
// No preceding %, this part isn't a variable.
returnString.Append(parts[index]);
// Since this isn't a variable, it didn't use the following %.
leadingPerc = true;
}
}
// Now add the last part, with a preceding % if there is one.
if (leadingPerc)
{
string message = "Unmatched % near the end of the input string: " + val;
if (tolerant)
{
_log.Warn(message);
returnString.Append("%");
}
else
{
throw new LoggingException(message);
}
}
returnString.Append(parts[parts.Length - 1]);
retVal = returnString.ToString();
}
}
return retVal;
}