Reputation: 913
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??
Upvotes: 0
Views: 87
Reputation: 573
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));
}
Upvotes: 0
Reputation: 38767
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"));
Upvotes: 2
Reputation: 101681
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.
Upvotes: 4