Search code examples
c#windows-phone-8streamwriterlistpickerisolatedstoragefile

Add data to an existing text file using IsolatedStorageFile


When the app runs for the first time I'm adding items to a text file like so:

     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"); 

                            }

I can then view this data in a ListPicker using the follow code when a button is pressed, again all works well:

 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();
        }

I now want to add to the text file programmatically, which I'm doing like so, once users have filled in some text blocks:

 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");

            } 

However, when I now go back to the previous page and click the button to view the entries in a ListPicker it turns out strange. The latest entry appears at the top with a large gap to the second place in the list. Adding another entry on top of that seems to hide the last entry.

The screenshot below should have to entries above the first "Chicago" entry. There should be a second Chicago entry that appears to have disappeared also.

Is there any way to browse to the created text file on the phone and see exactly how the data is laid out? This could give a clue.

enter image description here

Upon further investigation it appears when I write another line it is overwriting the existing text, rather than adding a new line. Any idea how to stop this?


Solution

  • I found some more documentation related to appending a file, which confirms my suspicion that the data was being overwritten.

    The method I used when adding data now looks like this:

    // ----------------------------------------------------------------
                // 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");
                    }
    
    
                }
    

    Another Stack Overflow post helped me with the solution that didn't appear during my first search:

    Does IsolatedStorage File.Append mode has an error with the the '\n'?