环境变量帮助类,支持通过环境变量取值,支持 string
,int
,long
,bool
,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpTest.Helpers;
/// <summary>
/// 环境变量帮助类
/// </summary>
internal class EnvironmentHelper
{
/// <summary>
/// 获取环境变量值,不匹配通通返回指定的默认值
/// </summary>
/// <param name="variable">环境变量名</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static string GetEnvironmentVariableValue(string variable, string defaultValue)
{
if (string.IsNullOrWhiteSpace(variable))
{
return defaultValue;
}
try
{
var value = Environment.GetEnvironmentVariable(variable);
if (value == null)
{
return defaultValue;
}
return value;
}
catch (Exception ex)
{
Console.WriteLine($"GetEnvironmentVariableValue({variable}) 转换失败,错误信息:{ex.Message}");
return defaultValue;
}
}
/// <summary>
/// 获取环境变量值,不匹配通通返回指定的默认值
/// </summary>
/// <param name="variable">环境变量名</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static long GetEnvironmentVariableValue(string variable, long defaultValue)
{
if (string.IsNullOrWhiteSpace(variable))
{
return defaultValue;
}
try
{
var value = Environment.GetEnvironmentVariable(variable);
if (value == null)
{
return defaultValue;
}
return long.Parse(value);
}
catch (Exception ex)
{
Console.WriteLine($"GetEnvironmentVariableValue({variable}) 转换失败,错误信息:{ex.Message}");
return defaultValue;
}
}
/// <summary>
/// 获取环境变量值,不匹配通通返回指定的默认值
/// </summary>
/// <param name="variable">环境变量名</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static int GetEnvironmentVariableValue(string variable, int defaultValue)
{
if (string.IsNullOrWhiteSpace(variable))
{
return defaultValue;
}
try
{
var value = Environment.GetEnvironmentVariable(variable);
if (value == null)
{
return defaultValue;
}
return int.Parse(value);
}
catch (Exception ex)
{
Console.WriteLine($"GetEnvironmentVariableValue({variable}) 转换失败,错误信息:{ex.Message}");
return defaultValue;
}
}
/// <summary>
/// 获取环境变量值,不匹配通通返回指定的默认值
/// </summary>
/// <param name="variable">环境变量名</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static bool GetEnvironmentVariableValue(string variable, bool defaultValue)
{
if (string.IsNullOrWhiteSpace(variable))
{
return defaultValue;
}
try
{
var value = Environment.GetEnvironmentVariable(variable);
if (value == null)
{
return defaultValue;
}
return bool.Parse(value);
}
catch (Exception ex)
{
Console.WriteLine($"GetEnvironmentVariableValue({variable}) 转换失败,错误信息:{ex.Message}");
return defaultValue;
}
}
}
发表评论