C#如何将环境变量作为字符串返回

时间:2016-04-26 17:19:14

标签: c# string environment-variables

在C#中,我想获取环境变量列表,并将它们转换为字符串。但是,当我执行代码时,我收到错误:

嵌入式声明不能是声明或带标签的声明

at string teststring = de.Value;

using System;
using System.Collections;
using System.IO;

class Sample
{

public static void Main()
{
    Console.WriteLine();
    Console.WriteLine("GetEnvironmentVariables: ");
    foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
        string teststring = de.Value;
        string testpath = String.Format("\nValue as string: ",teststring);
        Console.WriteLine(testpath);
        Console.WriteLine("\n  {0} = {1}", de.Key, de.Value);       
}
}    

我该如何解决这个问题?为什么会出现这种错误?

1 个答案:

答案 0 :(得分:1)

您需要在{区块周围放置}foreach,因为:

  1. 您有2个变量声明
  2. 您有超过1行的陈述
  3. public static void Main()
    {
        Console.WriteLine();
        Console.WriteLine("GetEnvironmentVariables: ");
        foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
        {
            string teststring = de.Value;
            string testpath = String.Format("\nValue as string: ",teststring);
            Console.WriteLine(testpath);
            Console.WriteLine("\n  {0} = {1}", de.Key, de.Value);
        }
    }