Когда приложение запускается в первый раз, я добавляю элементы в текстовый файл следующим образом:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
store.CreateDirectory("testLocations"); // Create a directory
IsolatedStorageFileStream rootFile = store.CreateFile("locations.txt"); // Create a file in the root.
rootFile.Close(); // Close File
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
string filePath = "locations.txt";
if (store.FileExists(filePath)) {
Debug.WriteLine("Files Exists");
StreamWriter sw =
new StreamWriter(store.OpenFile(filePath,
FileMode.Open, FileAccess.Write));
Debug.WriteLine("Writing...");
sw.WriteLine("Chicago, IL;");
sw.WriteLine("Chicago, IL (Q);");
sw.WriteLine("Dulles, VA;");
sw.WriteLine("Dulles, VA (Q);");
sw.WriteLine("London, UK;");
sw.WriteLine("London, UK (Q);");
sw.WriteLine("San Jose, CA;");
sw.WriteLine("San Jose, CA (Q);");
sw.Close();
Debug.WriteLine("Writing complete");
}
Затем я могу просмотреть эти данные в ListPicker, используя следующий код при нажатии кнопки, снова все работает хорошо:
private void locChoice(object sender, RoutedEventArgs e)
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
string filePath = "locations.txt";
if (store.FileExists(filePath))
{
Debug.WriteLine("Files Exists");
try
{
string fileData;
using (IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream("locations.txt", FileMode.Open, store))
{
using (StreamReader reader = new StreamReader(isoStream))
{
fileData = reader.ReadToEnd();
}
}
testLocationPicker.ItemsSource = fileData.Split(';');
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
testLocationPicker.Open();
}
Теперь я хочу добавить в текстовый файл программно, что я и делаю, как только пользователи заполнили некоторые текстовые блоки:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
string filePath = "locations.txt";
if (store.FileExists(filePath))
{
Debug.WriteLine("Files Exists");
StreamWriter sw =
new StreamWriter(store.OpenFile(filePath,
FileMode.Open, FileAccess.Write));
Debug.WriteLine("Writing...");
sw.WriteLine(locationName + ";"); // Semi Colon required for location separation in text file
sw.Close();
Debug.WriteLine(locationName + "; added");
Debug.WriteLine("Writing complete");
}
Однако, когда я теперь возвращаюсь на предыдущую страницу и нажимаю кнопку для просмотра записей в ListPicker, это получается странно. Последняя запись появляется вверху с большим отрывом от второго места в списке. Добавление еще одной записи поверх этой, кажется, скрывает последнюю запись.
Скриншот ниже должен иметь записи над первой записью «Чикаго». Должна быть вторая запись о Чикаго, которая, похоже, тоже исчезла.
Есть ли способ перейти к созданному текстовому файлу на телефоне и посмотреть, как именно расположены данные? Это может дать подсказку.
При дальнейшем расследовании выясняется, что когда я пишу другую строку, она перезаписывает существующий текст, а не добавляет новую строку. Любая идея, как остановить это?