user2992413
user2992413

Reputation: 77

Listbox items to data file c#

I'm tring to create a .dat file which contains all listbox items.

this is the writing code:

using (FileStream fs = new FileStream(@"Test.dat", FileMode.CreateNew))
{
    using (BinaryWriter w = new BinaryWriter(fs))
    {
         listBox1.Items.Add("Hello");
         listBox1.Items.Add("World");

         string[] words = new string[listBox1.Items.Count];
         listBox1.Items.CopyTo(words, 0);

         foreach(string word in words)
         {
             w.Write(word);
         }

         w.Close();

         fs.Close();
    }
}

and this is the reading code:

using (FileStream fs = new FileStream(@"Test.dat", FileMode.Open, FileAccess.Read))
{
    using (BinaryReader r = new BinaryReader(fs))
    {

        textBox1.Text = r.ReadString();

        r.Close();

        fs.Close();  
    }
}

But I only get the first item Hello from the listbox. Is there a way to get all the items from the listbox and make them a string data file ?

Upvotes: 1

Views: 458

Answers (3)

TaW
TaW

Reputation: 54453

To read from a BinaryReader, if that is what you need, you need a loop like this:

while (r.PeekChar() >= 0) textBox1.Text += r.ReadString() + "\r\n";

or else you get only the first string.

Peek checks to see if more is in the reader without advancing the file pointer, see here at MSDN

Of course to create a text file form the Listbox's items' texts LarsTech's answer is the way..

Upvotes: 0

LarsTech
LarsTech

Reputation: 81675

You are making it much more complicated:

To save the items:

File.WriteAllLines(@"Test.data", listBox1.Items.Cast<string>().ToArray());

And then to read them back, reverse the process:

listBox1.Items.AddRange(File.ReadAllLines(@"Test.data"));

Upvotes: 2

Kaitiff
Kaitiff

Reputation: 473

As you are using a foreach, why don't you use

for (int i = 0; i < listBox1.Items.Count; i++)
{
    w.Write(listBox1[i].ToString());
} 

Upvotes: 0

Related Questions