简体   繁体   English

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

[英]C# how do i return an environment variable as a string

in C#, I want to get the list of environment variables, and turn them into strings. 在C#中,我想获取环境变量的列表,并将其转换为字符串。 however, when I exectute the code, I get error: 但是,当我执行代码时,出现错误:

Embedded statement cannot be a declaration or labeled statement 嵌入式语句不能是声明或带标签的语句

at string teststring = de.Value; 在字符串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);       
}
}    

how can I fix this, and why is this error occurring? 如何解决此问题,为什么会发生此错误?

You need put { and } around your foreach block, because : 您需要将{}放在foreach块周围,因为:

  1. You have 2 variables declaration 您有2个变量声明
  2. You have more than 1 line of statement 您有超过1行的陈述

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM