环境变量(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);
                }

            }


            

        }
    }
}
posted @   陈希章  阅读(3386)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示