Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 向文件中添加多个项目_C# - Fatal编程技术网

C# 向文件中添加多个项目

C# 向文件中添加多个项目,c#,C#,为了将itemsListBox中的所有项目添加到文件中,我不确定需要在while循环中输入什么(或者是否有更好的方法)。现在(writer.writeline之前没有任何while循环),它只将最后一项添加到文件中。程序应该将项目添加到列表框并保存到文件中,然后在重新打开程序时加载它们。它还有一个标签,用于跟踪列表框中的项目数 private const string TO_DO_LIST = "to-do-list.txt"; public Form1() { InitializeCo

为了将itemsListBox中的所有项目添加到文件中,我不确定需要在while循环中输入什么(或者是否有更好的方法)。现在(writer.writeline之前没有任何while循环),它只将最后一项添加到文件中。程序应该将项目添加到列表框并保存到文件中,然后在重新打开程序时加载它们。它还有一个标签,用于跟踪列表框中的项目数

private const string TO_DO_LIST = "to-do-list.txt";
public Form1()
{
    InitializeComponent();
}

private void enterButton_Click(object sender, EventArgs e)
{
    AddItem();            
}

private void AddItem()
{
    itemsList.Items.Add(itemsBox.Text);
    numberOfItemsLabel.Text = itemsList.Items.Count.ToString();
    SaveItem();          
}

private void SaveItem()
{
    StreamWriter writer = File.CreateText(TO_DO_LIST);
    string newItem = itemsBox.Text;

    while ()//???
    {
        writer.WriteLine(newItem);
    }

    writer.Close();
}

private void Form1_Load(object sender, EventArgs e)
{
    try
    {
        StreamReader reader = File.OpenText(TO_DO_LIST);
        while (!reader.EndOfStream)
        {
            itemsList.Items.Add(reader.ReadLine());  
        }
    }
    catch (FileNotFoundException ex)
    {             
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}    

像这样的东西行吗

using (StreamWriter writer = File.CreateText(TO_DO_LIST))
{
    foreach (string text in itemsList.Items)
    {
        writer.WriteLine(text);
    }
};

使用
File.AppendAllLines
,只需一行即可完成此操作,它将打开或创建一个文件,向其添加文本,然后关闭该文件

第一个参数是文件路径,第二个参数是要添加的行的
IEnumerable

由于
ListBox.Items
是一个
ListBox.ObjectCollection
,我们需要将其转换为
IEnumerable
,以便使用
AppendAllLines
方法。这可以通过
Cast()
方法与
ToList()
结合来完成:

File.AppendAllLines(TO_DO_LIST,itemsList.Items.Cast().ToList());

这并没有改变任何事情,我肯定错过了一些非常简单的东西
File.AppendAllLines(TO_DO_LIST, itemsList.Items.Cast<String>().ToList());