I'm trying to save ListBox items in text file. The Items I have added from properties:
My code is:
private void button1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter st = new StreamWriter(S))
foreach (string aa in listBox1.Items)
st.WriteLine(listBox1.Items);
}
}
The output in text file is: System.Windows.Forms.ListBox+ObjectCollection
Just use the aa
into writeLine
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
{
using (StreamWriter st = new StreamWriter(S))
{
foreach (var aa in listBox1.Items)
st.WriteLine(aa.ToString());
}
}
}
As @davidsbro mentioned, you want aa
to be in the st.Writeline
as that is the actual string. listBox1.Items gives a class which Writeline can't handle as it doesn't know what you would want from Items
. So it outputs the name which is the result you got. If you want all the properties and other information about that Items
class you would have to serialize it and write to the file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.