1


I think my question is simple. I've searched but not found a solution for the method that I'm actually using.
I save the content of a listbox into a text file with success, but I'm having problem on load. For create the file, I use:

using(StreamWriter file = File.CreateText(path))

To write the content from the listbox to file, I use:

foreach (string content in listDOF.Items)
{
    file.WriteLine(content);
}

This works very well.
Now, I just need load the saved content with succes. I've tried:

if (File.Exists(filesrc))
{
    File.OpenRead(filesrc);
    string[] line = System.IO.File.ReadAllLines(filesrc);
    listDOF.Items.Add(line);
}

But this does not work and give me an exception.
How to do this correctily? Thanks all in advance! :)

3
  • Remove File.OpenRead(filesrc);, it is not necessary. Commented Aug 26, 2014 at 21:40
  • Thanks too @dasblinkenlight. This line was giving me a second exception in the save operation. Removing it and adding the Items.AddRange made my program works perfectly. Thanks! Commented Aug 26, 2014 at 21:56
  • @Hypister For future reference, when you get an exception, post it :) Commented Aug 27, 2014 at 7:53

1 Answer 1

3

You are adding an array of strings. The method to use is AddRange

string[] lines = System.IO.File.ReadAllLines(filesrc);
listDOF.Items.AddRange(lines);

The File.OpenRead is not needed. You could remove that line

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.