我可以使用“ StreamWriter”功能将文本保存在ListBox中吗?

private void button3_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFile1 = new SaveFileDialog();
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = "Text files|*.txt";
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
            saveFile1.FileName.Length > 0)
            {
                using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))

                {
                    sw.WriteLine(listBox1.Text);
                    sw.Close();
                }

最佳答案

属性ListBox.Text仅适用于所选项目。我怀疑您需要所有要素。如果存储了ListBox行,则可以这样做:

File.WriteAllLines(saveFile1.FileName, listBox1.Items.OfType<string>());

10-04 19:00