将c#console输出转换为Textbox输出

时间:2017-07-07 02:21:17

标签: c# wpf console

我是CSharp的新手,我知道你发现这个问题非常愚蠢,我需要知道如何将输出从控制台转换为文本框。感谢

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 个答案:

答案 0 :(得分:2)

Console.WriteLine在内部StreamWriter上调用WriteLine,其流是Console.Output。

你可以做的是使用另一个对象,比如StringBuilder并将结果写入StringBuilder,然后从Text的字符串结果中设置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();

或者在您的循环中,您只需在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);
    }