Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to save a listbox contents to a text file?

0 views
Skip to first unread message

Kudzu

unread,
Jun 9, 2002, 1:36:59 PM6/9/02
to
What is the best way to save the listbox contents to a text file? Right now I
have what is below. Is there an easier way I am missing? Something like
Delphi's TStrings.SaveToFile?

StreamWriter LWriter = File.CreateText(@"w:\source\voproci\bin\data.dat");
try
{
foreach (string LItem in lboxData.Items)
{
LWriter.WriteLine(LItem);
}
}
finally
{
LWriter.Close();
LWriter = null;
}


--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Posted by ELKNews 1.0.4-B
Empower your News Reader! http://www.atozedsoftware.com

Nicholas Paldino [.NET MVP]

unread,
Jun 9, 2002, 3:44:35 PM6/9/02
to
Kudzu,

I would create an array of strings that is the same length as the number
of items in the textbox. Then, iterate through each item in the listbox and
copy the string to the string array. Once that was done, I would use the
BinaryFormatter class to serialize the string array to a file, something
like this:

// mobjListBox is the listbox.
// Create the array.
string[] pstrStrings = new string[mobjListBox.Items.Count];

// Get the text for each item.
for(int pintIndex = 0; pintIndex < pstrStrings.Length; ++pintIndex)
// Copy the string representation to the listbox.
pstrStrings[pintIndex] =
mobjListBox.GetItemText(mobjListBox[pintIndex]);

// Create the binary formatter
BinaryFormatter pobjFormatter = new BinaryFormatter();

// Create the file stream.
FileStream pobjFileStream = new FileStream(@"c:\temp\contents.lbx");

// Serialize the data.
pobjFormatter.Serialize(pstrStrings, pobjFileStream);

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- casp...@caspershouse.com

"Kudzu" <cp...@hower.org> wrote in message
news:Xns9226A69...@127.0.0.1...

Kudzu

unread,
Jun 12, 2002, 7:26:06 AM6/12/02
to
"Nicholas Paldino [.NET MVP]" <casp...@caspershouse.com> wrote in
news:u2S$s9#DCHA.1764@tkmsftngp05:
> I would create an array of strings that is the same length as the
> number
> of items in the textbox. Then, iterate through each item in the listbox
> and copy the string to the string array. Once that was done, I would use
> the BinaryFormatter class to serialize the string array to a file,
> something like this:

Wow. Thats a lot of work just to save items to a text file. :)

--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

IntraWeb & FinalBuilder - http://www.AToZedSoftware.com

0 new messages