简体   繁体   English

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

[英]How do you write ListBox items to a text file?

The title basically says it all. 标题基本上说明了一切。 I am attempting to convert a ListBox in Visual Studio into a text file. 我正在尝试将Visual Studio中的列表框转换为文本文件。 I'm doing this in C#, as it is my most familiar language. 我正在用C#编写代码,因为它是我最熟悉的语言。

I would imagine that the code that I have would work, but for some reason, it does not. 我可以想象我拥有的代码可以工作,但是由于某种原因,它却行不通。 Here is the code that I have so far: 这是我到目前为止的代码:

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

Any help would be greatly appreciated! 任何帮助将不胜感激!

Something like this 像这样

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

Enumerable.Cast(IEnumerable) Method Enumerable.Cast(IEnumerable)方法

Casts the elements of an IEnumerable to the specified type. 将IEnumerable的元素强制转换为指定的类型。

File.WriteAllLines Method File.WriteAllLines方法

Creates a new file, writes one or more strings to the file, and then closes the file. 创建一个新文件,向该文件写入一个或多个字符串,然后关闭该文件。

welcome to StackOverflow ! 欢迎使用StackOverflow!

I just run a very simple example, and apart of making use of using as StreamWriter is a disposable object, all went fine ... Im just wondering if you have permission to write to the C: drive, and as TheGeneral mentioned, you do need to close the file, hence I've use the using statement, as it does close and dispose the object in one go. 我只是运行了一个非常简单的示例,除了using用作StreamWriter是一个可抛弃的对象,一切都很好……我只是想知道您是否有权写入C:驱动器,并且正如TheGeneral所述,您确实需要关闭文件,因此我使用了using语句,因为它确实关闭并一次性处理了对象。

my simple example: 我的简单示例:

在此处输入图片说明

where the file write is: 文件写入的位置:

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());
        }
    }
}

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

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