Create and save multiple list of text into Isolated Storage
How do I create more than one list of text data and save it into the isolated storage? I need to retrieve and display different saved list as well.
I am doing an application like a drink list where user can create multiple drink list containing many different kinds of drink.
I can only create and save one list of drink text at the moment. If I were to add more drink text inside the list again and save it, the list will be overwritten by the latest different drink text.
// Save List of drink text
private void addListBtn_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
storage.CreateDirectory("ListFolder");
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ListFolder\\savedList.txt", FileMode.OpenOrCreate, storage));
for (int i = 0; i < (Application.Current as App).userDrinksList.Count; i++)
{
String drink = (Application.Current as App).userDrinksList[i].ToString();
writeFile.WriteLine(drink.ToString());
}
writeFile.Close();
MessageBox.Show("List added into favourite list.");
}
// Displ开发者_开发百科ay saved lists
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader readFile = null;
{
readFile = new StreamReader(new IsolatedStorageFileStream("ListFolder\\savedList.txt", FileMode.Open, storage));
listNumberListBox.Items.Add(readFile.ReadToEnd());
readFile.Close();
}
}
You are saving it as savedList.txt. You need to save each list as a separate file. eg list1.txt, list2.txt etc.
Perhaps you also need a list of lists so you know which file = which list.
Your addListBtn_Click method is assuming it can find the list of drinks in a userDrinksList member of your Application instance, however your PhoneApplicationPage_Loaded method doesn't populate that member.
In your PhoneApplicationPage_Loaded method you could do:
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
using(var stream = storage.OpenFile("ListFolder\\savedList.txt", FileMode.Open))
using(StreamReader readFile = new StreamReader(stream))
{
for (string line = readFile.ReadLine(); line != null; line = readFile.ReadLine())
{
listNumberListBox.Items.Add(line);
((App) Application.Current).userDrinksList.Add(line)
}
}
The 'usings' ensure that the resources are properly closed/disposed, so you don't need to explicitly close. You were reading in the complete contents - you need to read it in line by line.
精彩评论