I noticed, that method Environment.ExpandEnvironmentVariables() does not returns values for some system variables such as %date%, %time%, %homeshare% etc... Why?

有帮助吗?

解决方案

%HOMESHARE% may simply be undefined (it's not defined in all situations). %DATE% and %TIME% are dynamic variables that AFAIK are not available outside of CMD (same goes for e.g. %CD% and %ERRORLEVEL%).

其他提示

@Ansgar Wiechers is of course correct, I thought that I provide the code to the following function, which attempts to replace (some) of the CMD.EXE specific variables as well.

    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;
    }

The definition for the GetNumaHighestNodeNumber P/Invoke is as follows:

    [DllImport(KernelDll)]
    [return: MarshalAsAttribute(UnmanagedType.Bool)]
    public static extern bool GetNumaHighestNodeNumber([Out] out uint   HighestNodeNumber);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top