简体   繁体   English

如何将列表框项目保存在文本文件中?

[英]how to save listbox items in text file?

I'm trying to save ListBox items in text file. 我正在尝试将ListBox项目保存在文本文件中。 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 文本文件中的输出为:System.Windows.Forms.ListBox + ObjectCollection

Just use the aa into writeLine 只需使用aa进入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. 正如@davidsbro所提到的,您希望aa出现在st.Writeline因为这是实际的字符串。 listBox1.Items gives a class which Writeline can't handle as it doesn't know what you would want from Items . listBox1.Items提供了Writeline无法处理的类,因为它不知道您要从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. 如果要获取有关该Items类的所有属性和其他信息,则必须对其进行序列化并将其写入文件。

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

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