如何将 ListBox 项写入文本文件?

How do you write ListBox items to a text file?

标题基本上说明了一切。我正在尝试将 Visual Studio 中的列表框转换为文本文件。我在 C# 中执行此操作,因为它是我最熟悉的语言。

我原以为我的代码可以工作,但由于某种原因,它没有。这是我到目前为止的代码:

System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(@"C:\WhosTalking\List.txt");
foreach (var item in list.Items)
{
    SaveFile.WriteLine(item.ToString());
}

如有任何帮助,我们将不胜感激!

像这样

File.WriteAllLines("SomePath",listBox1.Items.Cast<string>());

Enumerable.Cast(IEnumerable) Method

Casts the elements of an IEnumerable to the specified type.

File.WriteAllLines Method

Creates a new file, writes one or more strings to the file, and then closes the file.

欢迎使用 Whosebug!

我只是 运行 一个非常简单的例子,除了利用 using 因为 StreamWriter 是一个一次性对象,一切都很好......我只是想知道 如果您有权限 写入 C: 驱动器,并且正如 TheGeneral 提到的,您确实需要关闭该文件,因此我已经使用 using 语句,因为它会一次性关闭并处理对象。

我的简单示例:

写入文件的位置:

private void btnSave_Click(object sender, EventArgs e)
{
    using (System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(@"D:\List.txt"))
    {
        foreach (var item in listBox.Items)
        {
            SaveFile.WriteLine(item.ToString());
        }
    }
}