Reputation: 61
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
Reputation: 3189
See code below. Your original had a couple of bugs:
You're closing txt
inside the loop used to write the listbox items to the text file.
You don't need the \n
in txt.WriteLine("\n" + item.ToString());
. WriteLine
provides the newline
You need a loop to read the text file and re-add each line back tot he listbox
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");
}
}
Upvotes: 1
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
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
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