0

I had written a list object to a file like this

 private List<string> _cacheFileList=new List<string>(4);
_cacheFileList.Add("Something");
    using (StreamWriter file = new StreamWriter(@"cache.bin")) 
                {
                    file.Write(_cacheFileList);
                }

Now how could I retrieve whole list object??

0

3 Answers 3

4

Instead of using StreamWriter like that, use BinaryFormatter to serialize your list. Then you can easily retrieve your list back by deserializing. MSDN has a good example about how to do that.

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

Comments

2

If you just want a text file with a single line per list entry, you could try the code below. Of course, you would need error handling and need to ensure that the strings in the list did not contain newlines.

// Write
List<string> _listA = new List<string>(4);
_listA.Add("Test");
_listA.Add("Test2");
_listA.Add("Test3");
_listA.Add("Test4");
System.IO.File.WriteAllLines("test.txt", _listA);

// Read
List<string> _listB = new List<string>(4);
_listB.AddRange(System.IO.File.ReadAllLines("test.txt"));

Comments

0

If you want just write your list line by line then you can modify your code like this:

var cacheFileList = new List<string>(4);
cacheFileList.Add("Something");

using (var file = new StreamWriter(@"cache.bin"))
{
    file.Write(string.Join("\r\n", cacheFileList));
}

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.