Aatroxon
Aatroxon

Reputation: 61

New line after all loaded items in listbox (C#)

So I want something like:

item1

item2

but I get:

item1item2

Please help!

My current code:

TextWriter txt = new StreamWriter("IP.txt");
foreach (var item in listBox1.Items)
{
    txt.WriteLine("\n" + item.ToString());
    txt.Close();
}

listBox1.Items.Clear();
TextReader reader = new StreamReader("IP.txt");

listBox1.Items.Add("\n" + reader.ReadToEnd());
reader.Close();

Upvotes: 0

Views: 1070

Answers (4)

VA systems engineer
VA systems engineer

Reputation: 3189

See code below. Your original had a couple of bugs:

  1. You're closing txt inside the loop used to write the listbox items to the text file.

  2. You don't need the \n in txt.WriteLine("\n" + item.ToString());. WriteLine provides the newline

  3. You need a loop to read the text file and re-add each line back tot he listbox

  4. I suggest you use using to ensure files are closed and objects are disposed in case the program crashes for some reason

Note: I added " text from file" to the text added back to the listbox to demonstrate that the listbox was loaded from the text file

listBox1.Items.Add("Item1");
listBox1.Items.Add("Item2");

 using (TextWriter txt = new StreamWriter("IP.txt"))
 {
     foreach (var item in listBox1.Items)
     {
         txt.WriteLine(item.ToString());
     }
 }

 listBox1.Items.Clear();

 using (StreamReader inputFile = File.OpenText("IP.txt"))
 {
     while (!inputFile.EndOfStream)
     {
         listBox1.Items.Add(inputFile.ReadLine() + " text from file");
     }
 }

enter image description here

Upvotes: 1

Slaven Tojić
Slaven Tojić

Reputation: 3014

Use Environment.NewLine instead of "\n":

TextWriter txt = new StreamWriter("IP.txt");
foreach (var item in listBox1.Items)
{
    txt.WriteLine(Environment.NewLine + item.ToString());
    txt.Close();
}

listBox1.Items.Clear();
TextReader reader = new StreamReader("IP.txt");

listBox1.Items.Add(Environment.NewLine + reader.ReadToEnd());
reader.Close();

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

Get rid of Reader/Writer but use File and let .Net solve the task for you:

Writing to file:

File.WriteAllLines("IP.txt", listBox1
  .Items
  .OfType<Object>() 
  .Select(item => item.ToString()));

Reading from file:

listBox1.Items.Clear();

listBox1.Items.AddRange(File.ReadAllLines("IP.txt"));

Upvotes: 1

Shivani Katukota
Shivani Katukota

Reputation: 859

ReadToEnd() reads all characters from the current position to the end of the text reader and returns them as one string. Instead use this:

string[] lines = File.ReadAllLines("IP.txt");

This will have all your lines. You can now iterate on the array and create list box items.

Upvotes: 0

Related Questions