如何将列表保存到文件中,然后将项目读回ListBox
本文关键字:项目 然后 ListBox 列表 存到文件 | 更新日期: 2023-09-27 18:25:04
我试图在不使用Serialize的情况下将一个简单列表保存到一个文件中。这可能吗?
public partial class Form1 : Form
{
public List<string> _testList = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int _add = 0;
string _addString ="";
for (int i = 0; i < 5; i++)
{
_add =+ i;
_addString = Convert.ToString(_add);
_testList.Add(_addString);
}
TextWriter tw = new StreamWriter("SavedList.txt", true);
foreach (string s in _testList)
tw.WriteLine(s);
tw.Close();
StreamReader streamReader = new StreamReader("SavedList.txt");
// Read the data to the end of the stream.
listBox1.Text = streamReader.ReadToEnd();
// Close the text stream reader.
streamReader.Close();
// Close the file stream.
//fileStream.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
这不会发出任何错误,但不会执行任何操作。
如果必要的话,我会使用Serialize,但是怀疑这不是必要的。是吗?
您可以使用File
类来实现这一点。
File.WriteAllLines("SavedList.txt", _testList.ToArray());
要读回,您可以使用:
string[] lines = File.ReadAllLines("SavedList.txt");
foreach (string line in lines)
listBox1.Items.Add(line);
您的问题是ListBox
的Text
字段不能那样工作。
更改:
listBox1.Text = streamReader.ReadToEnd();
至:
foreach(string s in streamReader.ReadToEnd().Split(new string[]{"'r'n"}))//!!!the end of line characters may differ depending on your system!!!
{
listBox1.Items.Add(s);
}
"文本"字段保存当前选定的文本。它不用于向列表中添加项目。