简体   繁体   English

c# - 从文本文件中读取行并添加到列表框中

[英]c# - Reading lines from text file and adding to listbox


I think my question is simple. 我认为我的问题很简单。 I've searched but not found a solution for the method that I'm actually using. 我已搜索但未找到我实际使用的方法的解决方案。
I save the content of a listbox into a text file with success, but I'm having problem on load. 我成功地将列表框的内容保存到文本文件中,但是我在加载时遇到问题。 For create the file, I use: 为了创建文件,我使用:

using(StreamWriter file = File.CreateText(path))

To write the content from the listbox to file, I use: 要将列表框中的内容写入文件,我使用:

foreach (string content in listDOF.Items)
{
    file.WriteLine(content);
}

This works very well. 这非常有效。
Now, I just need load the saved content with succes. 现在,我只需要成功加载已保存的内容。 I've tried: 我试过了:

if (File.Exists(filesrc))
{
    File.OpenRead(filesrc);
    string[] line = System.IO.File.ReadAllLines(filesrc);
    listDOF.Items.Add(line);
}

But this does not work and give me an exception. 但这不起作用,并给我一个例外。
How to do this correctily? 如何正确地做到这一点? Thanks all in advance! 提前谢谢! :) :)

You are adding an array of strings. 您正在添加一个字符串数组。 The method to use is AddRange 使用的方法是AddRange

string[] lines = System.IO.File.ReadAllLines(filesrc);
listDOF.Items.AddRange(lines);

The File.OpenRead is not needed. 不需要File.OpenRead。 You could remove that line 你可以删除该行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM