C# 如何将数组的内容写入文本文件?C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13023147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:23:03  来源:igfitidea点击:

How to write contents of an array to a text file? C#

c#arraysfiletext

提问by Boneyards

I'm trying to write the contents of an array to a text file. I've created the file, assigned text boxes to the array (not sure if correctly). Now I want to write the contents of the array to a text file. The streamwriter part is where I'm stuck at the bottom. Not sure of the syntax.

我正在尝试将数组的内容写入文本文件。我已经创建了文件,为数组分配了文本框(不确定是否正确)。现在我想将数组的内容写入文本文件。流作家部分是我被困在底部的地方。不确定语法。

if ((!File.Exists("scores.txt"))) //Checking if scores.txt exists or not
{
    FileStream fs = File.Create("scores.txt"); //Creates Scores.txt
    fs.Close(); //Closes file stream
}
List<double> scoreArray = new List<double>();
TextBox[] textBoxes = { week1Box, week2Box, week3Box, week4Box, week5Box, week6Box, week7Box, week8Box, week9Box, week10Box, week11Box, week12Box, week13Box };

for (int i = 0; i < textBoxes.Length; i++)
{
    scoreArray.Add(Convert.ToDouble(textBoxes[i].Text));
}
StreamWriter sw = new StreamWriter("scores.txt", true);

采纳答案by Enigmativity

You could just do this:

你可以这样做:

System.IO.File.WriteAllLines("scores.txt",
    textBoxes.Select(tb => (double.Parse(tb.Text)).ToString()));

回答by Miguel Angelo

You may try to write to the file before you close it... after the FileStream fs = File.Create("scores.txt");line of code.

您可以尝试在关闭文件之前写入文件...在FileStream fs = File.Create("scores.txt");代码行之后。

You may also want to use a usingfor that. Like this:

您可能还想为此使用 a using。像这样:

if ((!File.Exists("scores.txt"))) //Checking if scores.txt exists or not
    {
        using (FileStream fs = File.Create("scores.txt")) //Creates Scores.txt
        {
            // Write to the file here!
        }
    }

回答by opewix

using (FileStream fs = File.Open("scores.txt"))
{
    StreamWriter sw = new StreamWriter(fs);
    scoreArray.ForEach(r=>sw.WriteLine(r));
}

回答by Herbert

You can convert your list to an array then write the all array textfile

您可以将列表转换为数组,然后写入所有数组文本文件

double[] myArray = scoreArray.ToArray();
ile.WriteAllLines("scores.txt", Array.ConvertAll(myArray, x => x.ToString()));