2017-07-07 128 views
0

我很新的CSharp,我知道你發現這個問題很愚蠢,我需要一個想法如何將輸出從控制檯轉換爲文本框。感謝轉換c#控制檯輸出到文本框輸出

foreach (DriveInfo d in allDrives) 
{ 
    Console.WriteLine("Drive {0}", d.Name); 
    Console.WriteLine(" Drive type: {0}", d.DriveType); 
    if (d.IsReady == true) 
    { 
     Console.WriteLine(" Volume label: {0}", d.VolumeLabel); 
     Console.WriteLine(" File system: {0}", d.DriveFormat); 
     Console.WriteLine(
      " Available space to current user:{0, 15} bytes", 
      d.AvailableFreeSpace); 

     Console.WriteLine(
      " Total available space:   {0, 15} bytes", 
      d.TotalFreeSpace); 

     Console.WriteLine(
      " Total size of drive:   {0, 15} bytes ", 
      d.TotalSize); 
    } 
    Console.ReadKey(true); 
} 
+1

我在這裏看到了WPF標籤。那麼,你的意思是WPF文本框? –

+0

這只是簡單的使用'DriveInfo'而沒有值轉換爲任何其他平臺 –

+0

您可能要考慮在此論壇中搜索諸如「將控制檯轉換爲WPF」之類的關鍵短語。像這樣:https://stackoverflow.com/search?q=convert+console+to+wpf –

回答

2

Console.WriteLine是調用內部StreamWriter其流是Console.Output一個的WriteLine。

你可以做的是使用另一個對象,像StringBuilder,寫你的結果到StringBuilder,然後從StringBuilder.ToString()

StringBuilder sb = new StringBuilder(); 
sb.AppendFormat("Drive {0}\n", d.Name); 
sb.AppendFormat(" Drive type: {0}\n", d.DriveType); 
    if (d.IsReady == true) 


    { 
     sb.AppendFormat(" Volume label: {0}\n", d.VolumeLabel); 
     sb.AppendFormat(" File system: {0}\n", d.DriveFormat); 
     sb.AppendFormat(
      " Available space to current user:{0, 15} bytes\n", 
      d.AvailableFreeSpace); 

     sb.AppendFormat(
      " Total available space:   {0, 15} bytes\n", 
      d.TotalFreeSpace); 

     sb.AppendFormat(
      " Total size of drive:   {0, 15} bytes \n", 
      d.TotalSize); 
    } 
txtBox1.Text = sb.ToString(); 

或者在你的循環中的字符串結果集Text,你可以添加新行文本到你的TextBox

txtBox.Text += String.Format(("Drive {0}\n", d.Name); 
    txtBox.Text += String.Format((" Drive type: {0}\n", d.DriveType); 
    if (d.IsReady == true) 


    { 
     txtBox.Text += String.Format((" Volume label: {0}\n", d.VolumeLabel); 
     txtBox.Text += String.Format((" File system: {0}\n", d.DriveFormat); 
     txtBox.Text += String.Format((
      " Available space to current user:{0, 15} bytes\n", 
      d.AvailableFreeSpace); 

     txtBox.Text +=String.Format((
      " Total available space:   {0, 15} bytes\n", 
      d.TotalFreeSpace); 

     txtBox.Text +=String.Format((
      " Total size of drive:   {0, 15} bytes \n", 
      d.TotalSize); 
    }