Добавьте данные в существующий текстовый файл с помощью IsolatedStorageFile.

Когда приложение запускается в первый раз, я добавляю элементы в текстовый файл следующим образом:

     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, это получается странно. Последняя запись появляется вверху с большим отрывом от второго места в списке. Добавление еще одной записи поверх этой, кажется, скрывает последнюю запись.

Скриншот ниже должен иметь записи над первой записью «Чикаго». Должна быть вторая запись о Чикаго, которая, похоже, тоже исчезла.

Есть ли способ перейти к созданному текстовому файлу на телефоне и посмотреть, как именно расположены данные? Это может дать подсказку.

введите здесь описание изображения

При дальнейшем расследовании выясняется, что когда я пишу другую строку, она перезаписывает существующий текст, а не добавляет новую строку. Любая идея, как остановить это?


person Dan James Palmer    schedule 19.05.2014    source источник


Ответы (1)


Я нашел еще несколько документов, связанных с добавлением файла, что подтверждает мое подозрение, что данные перезаписываются.

Метод, который я использовал при добавлении данных, теперь выглядит так:

// ----------------------------------------------------------------
            // Write the friend name to the locations text file upon submission
            // ----------------------------------------------------------------

            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)
            byte[] data = Encoding.UTF8.GetBytes(locationName + ";");
            string filePath = "locations.txt";

            if (store.FileExists(filePath))
            {
                using (var stream = new IsolatedStorageFileStream(filePath, FileMode.Append, store))
                {

                    Debug.WriteLine("Writing...");
                    stream.Write(data, 0, data.Length);   // Semi Colon required for location separation in text file
                    stream.Close();
                    Debug.WriteLine(locationName + "; added");
                    Debug.WriteLine("Writing complete");
                }


            }

Другой пост Stack Overflow помог мне с решением, которое не появилось во время моего первого поиска:

Есть ли в режиме IsolatedStorage File.Append режим ошибка с '\n'?

person Dan James Palmer    schedule 19.05.2014