如何将循环文本字符串打印到新文本文件

时间:2015-02-13 00:46:06

标签: c#

我正在创建一个应用程序,它显示-40 - 40的摄氏度表及其华氏度等值。我希望将显示的文本写入文本文件。

我理解循环,但我无法弄清楚如何将其打印到文本文件中。

到目前为止,这是我的代码:

for (int c = -40; c <= 40; c++)
{
    // Celsius convert to Fahrenheit //
    f = 9.0 / 5.0 * c + 32;

    // print into listbox //
    tempListBox.Items.Add("Celsius = " + c.ToString("n3") + " " + "Fahrenheit = " + f.ToString("n3"));
}

2 个答案:

答案 0 :(得分:1)

 using (StreamWriter sw = new StreamWriter("file.txt"))
        {
            foreach (string item in tempListBox)
            {
                sw.WriteLine(item);
            }
        }

答案 1 :(得分:1)

好的,您需要先在文件顶部添加以下参考文献...

using System.IO;
using System.Collections;
using System.Collections.Generic;

然后在你的方法中,像这样写代码......

        var tempOutputList = new List<string>();

        for (var c = -40; c <= 40; c++)
        {
            // Celsius convert to Fahrenheit//
            var f = 9.0 / 5.0 * c + 32;
            var tempOutputText = "Celsius = " + c.ToString("n3") + " " + "Fahrenheit = " + f.ToString("n3");

            tempOutputList.Add(tempOutputText);
            tempListBox.Items.Add(tempOutputText);
        }

        using (var file = new StreamWriter(@"C:\tempFile.txt"))
        {
            foreach (string tempOutput in tempOutputList)
            {
                file.WriteLine(tempOutput);
            }
        }

为什么此代码更好,是因为您没有使用&#39;项目&#39;在ListBox中,而是一个简单的List,其属性设置为&#39; string&#39;。进一步的调查表明,您还可以将ListBox项目绑定到列表中。我会留下那个让你弄明白的。