简体   繁体   English

将窗体列表框保存到文本文件C#

[英]Saving windows form listbox to a text file C#

I'm trying to save the contents of a listbox into a text file. 我正在尝试将列表框的内容保存到文本文件中。 and it works, but instead of the text entered into the list box, I get this: 它工作,但我得到这个,而不是输入到列表框中的文本:

System.Windows.Forms.ListBox+ObjectCollection

Here is the relevant code I'm using for the form itself. 这是我用于表单本身的相关代码。

listString noted = new listString();
        noted.newItem = textBox2.Text;
        listBox1.Items.Add(textBox2.Text);

        var radioOne = radioButton1.Checked;

        var radioTwo = radioButton2.Checked;

        var radioThree = radioButton3.Checked;

        if (radioButton1.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("C:\\windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else if (radioButton2.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("C:\\Users\\windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else if (radioButton3.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("../../../../windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else
        {
            MessageBox.Show("Please select a file path.");
        }
    }

The class is just a simple one: 这堂课只是一个简单的课程:

 namespace Decisions
 {
     public class listString
     {
         public string newItem {get; set;}

         public override string ToString()
         {
             return string.Format("{0}", this.newItem);
         }
     }
 }

You will have to write the items one by one: 您必须逐个编写项目:

using (StreamWriter sw = new StreamWriter("C:\\windowsNotes.txt") {
    foreach (var item in listBox1.Items) {
        sw.WriteLine(item.ToString());
    }
}

You cannot just do 你不能这样做

   sw.Write(listBox1.Items);

as it's calling .ToString() on the collection object itself. 因为它在集合对象本身上调用.ToString()。

Try something like: 尝试类似的东西:

   sw.Write(String.Join(Environment.NewLine, listBox1.Items));

Or loop through each item and ToString the individual item. 或者遍历每个项目并ToString单个项目。

You're writing the ToString of the collection to the output stream rather than of the elements of the collection. 您正在将集合的ToString写入输出流而不是集合的元素。 Iterating over the collection and outputting each one individually would work, and I'm sure there there's a succint Linq (or even more obvious) way of doing that. 对集合进行迭代并逐个输出每个集合都可以正常工作,我确信有一种简单的Linq(甚至更明显)的方法。

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

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