简体   繁体   中英

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. however, when I exectute the code, I get error:

Embedded statement cannot be a declaration or labeled statement

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

how can I fix this, and why is this error occurring?

You need put { and } around your foreach block, because :

  1. You have 2 variables declaration
  2. You have more than 1 line of statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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