环境变量(Environment Variable)那点事

在Windows编程中,我们可能经常需要用到环境变量。它其实相当于是操作系统级别的一个配置文件。

.NET编程中可以很方便地访问到这些环境变量,下面的代码就演示了这个过程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //依次打印三种级别的环境变量

            Console.WriteLine("计算机的环境变量");
            foreach (DictionaryEntry item in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine))
            {
                Console.WriteLine("{0}:{1}",item.Key,item.Value);
            }
            Console.WriteLine();


            Console.WriteLine("用户的环境变量");

            foreach (DictionaryEntry item in Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User))
            {
                Console.WriteLine("{0}:{1}", item.Key, item.Value);
            }
            Console.WriteLine();

            Console.WriteLine("进程的环境变量");

            foreach (DictionaryEntry item in Environment.GetEnvironmentVariables())
            {
                Console.WriteLine("{0}:{1}", item.Key, item.Value);
            }

            //一次性打印所有三种环境变量(直接利用枚举器的遍历

            var targets = Enum.GetNames(typeof(EnvironmentVariableTarget));
            foreach (var target in targets)
            {
                Console.WriteLine("{0}级别的环境变量", target);
                EnvironmentVariableTarget t =(EnvironmentVariableTarget) Enum.Parse(typeof(EnvironmentVariableTarget), target);

                foreach (DictionaryEntry item in Environment.GetEnvironmentVariables(t))
                {
                    Console.WriteLine("{0}:{1}", item.Key, item.Value);
                }

            }


            

        }
    }
}

你可能感兴趣的:(编程,c,windows,.net,String,Class)