簡體   English   中英

C#如何將環境變量作為字符串返回

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

在C#中,我想獲取環境變量的列表,並將其轉換為字符串。 但是,當我執行代碼時,出現錯誤:

嵌入式語句不能是聲明或帶標簽的語句

在字符串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);       
}
}    

如何解決此問題,為什么會發生此錯誤?

您需要將{}放在foreach塊周圍,因為:

  1. 您有2個變量聲明
  2. 您有超過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