我注意到,该方法Environment.ExpandEnvironmentVariables()
不返回某些系统变量的值,例如%date%
,%time%
等%homeshare%
...为什么?
问问题
1934 次
2 回答
4
%HOMESHARE%
可能只是未定义(并非在所有情况下都定义)。%DATE%
并且%TIME%
是 AFAIK 在外部不可用的动态变量CMD
(例如%CD%
和 也是如此%ERRORLEVEL%
)。
于 2013-07-28T19:08:15.940 回答
3
@Ansgar Wiechers当然是正确的,我认为我将代码提供给以下函数,该函数也尝试替换(某些)CMD.EXE
特定变量。
public static string ExpandEnvironmentVariables(string str)
{
// Environment.ExpandEnvironmentVariables() does this as well, but we don't rely on that.
if (str == null)
throw new ArgumentNullException("str");
// First let .NET Fx version do its thing, because then:
//
// - Permission checks, etc. will already be done up front.
// - Should %CD% already exists as a user defined variable, it will already be replaced,
// and we don't do it by the CurrentDirectory later on. This behavior is consistent with
// what CMD.EXE does.
// Also see http://blogs.msdn.com/b/oldnewthing/archive/2008/09/26/8965755.aspx.
//
str = Environment.ExpandEnvironmentVariables(str);
// The following is rather expensive, so a quick check if anything *could* be required at all
// seems to be warrented.
if (str.IndexOf('%') != -1)
{
const StringComparison comp = StringComparison.OrdinalIgnoreCase;
var invariantCulture = CultureInfo.InvariantCulture;
var now = DateTime.Now;
str = str.Replace("%CD%", Environment.CurrentDirectory, comp);
str = str.Replace("%TIME%", now.ToString("T") + "," + now.ToString("ff"), comp);
str = str.Replace("%DATE%", now.ToString("d"), comp);
str = str.Replace("%RANDOM%", s_random.Next(0, Int16.MaxValue).ToString(invariantCulture), comp);
// Debatable, but we replace them anyway to make sure callers don't "crash" because
// them not being unexpanded, and becase we "can".
str = str.Replace("%CMDEXTVERSION%", "2", comp); // This is true at least on XP to Server 2008R2
str = str.Replace("%CMDCMDLINE%", Environment.CommandLine, comp);
uint nodeNumber;
if (!NativeMethods.GetNumaHighestNodeNumber(out nodeNumber))
{
nodeNumber = 0;
}
str = str.Replace("%HIGHESTNUMANODENUMBER%", nodeNumber.ToString(invariantCulture), comp);
}
return str;
}
P/Invoke的定义GetNumaHighestNodeNumber
如下:
[DllImport(KernelDll)]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool GetNumaHighestNodeNumber([Out] out uint HighestNodeNumber);
于 2013-07-29T09:40:37.423 回答