none
Appending text to file

    Question

  • guys

    I tried using the following to append a string to a csv file

    string dave = Environment.NewLine + T1.Text + "," + T2.Text + "," + T3.Text + "," + T4.Text + "," + T5.Text + "," + T6.Text;
                StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
                var folder = KnownFolders.DocumentsLibrary;
                var file = await folder.GetFileAsync("sample.csv");
                await FileIO.AppendTextAsync(file, dave);

    I am getting an error saying FileIO does not exist in this context

    I think its because i'm writing this for windows phone and the code is some i have used in a windows 8.1 app

    Any idea how i achieve this. the file is stored in the documents folder of my phone and i need to append the string "dave"  to whats already there

    Thanks

    Mark

    Saturday, January 25, 2014 5:36 PM

Answers

  • I tested the code before posting. It works.

    Here's a complete example:

    1. Open a new Windows Phone project.
    2. Put this in MainPage.xaml (add the Button):
          <Grid x:Name="LayoutRoot" Background="Transparent">
              <Grid.RowDefinitions>
                  <RowDefinition Height="Auto"/>
                  <RowDefinition Height="*"/>
              </Grid.RowDefinitions>
      
              <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
                  <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
                  <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
                  <Button Content="append file" Tap="Button_Tap"/>
              </StackPanel>
          </Grid>
    3. Put this in MainPage.xaml.cs:
      using System.Threading.Tasks;
      using Windows.Storage;
      using System.IO;
      
      
      ...
      
      
          public partial class MainPage : PhoneApplicationPage
          {
              int index = 1;
      
              public MainPage()
              {
                  InitializeComponent();
              }
      
              private async void Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
              {
                  string dave = Environment.NewLine + "dave " + index++;
                  await AppendAsync("sample.csv", dave);
              }
      
              private async Task AppendAsync(string filename, string text)
              {
                  StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
                  using (Stream stream = await file.OpenStreamForWriteAsync())
                  {
                      stream.Seek(0, SeekOrigin.End);
                      using (StreamWriter writer = new StreamWriter(stream))
                      {
                          await writer.WriteAsync(text);
                          await writer.FlushAsync();
                      }
                  }
              }
          }
    4. Run the app and tap the button 3 times.
    5. Open an isolated storage explorer tool. In the top level of isolated storage, you will find a file named sample.csv with 3 lines:
      dave 1
      dave 2
      dave 3


    Richard Woo
    • Marked as answer by wambaugh1 Monday, January 27, 2014 6:12 AM
    Sunday, January 26, 2014 11:08 AM
  • Dont know why you cant see it in windows file explorer
    Isolated storage is normally private, secured data accessible only by the phone app. These are developer tools that only work on a developer unlocked phone (or emulator), and only for a developer app you deployed through Visual Studio or xap deployment tool. You cannot examine the isolated storage of an app installed from the Store. Only that app can access its own isolated storage.
    Sunday, January 26, 2014 7:30 PM

All replies

  • Hi

    Yes the code you have shown is a windows 8.1 code. 

    Please refer the link below

    http://msdn.microsoft.com/en-us/library/ff604992.aspx

    Here is the sample code

       private async System.Threading.Tasks.Task SaveAsync(string filename, string text)
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

                using (Stream stream = await file.OpenStreamForWriteAsync())
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {

                        await writer.WriteAsync(text);

                        await writer.FlushAsync();
                    }
                }
            }

    Regards


    Varun Ravindranath


    Saturday, January 25, 2014 7:06 PM
  • Hi Varun

    Thanks for the sample but I can work out how to call it

    Basically I have a save button when i Tap it i would like to run the code so that it saves a line of tet to a csv file. The change the code to meet my situation which is as follows

     private async System.Threading.Tasks.Task SaveAsync(string filename, string text)
            {
                string dave = Environment.NewLine + T1.Text + "," + T2.Text + "," + T3.Text + "," + T4.Text + "," + T5.Text + "," + T6.Text;
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(dave, CreationCollisionOption.OpenIfExists);
                using (Stream stream = await file.OpenStreamForWriteAsync())
                {
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        await writer.WriteAsync(dave);
                        await writer.FlushAsync();
                    }
                }
            }

    I have tried putting it the tap event but it just hangs

    Any ideas

    Mark

    Saturday, January 25, 2014 8:09 PM
  • Varun's code overwrites the file. You need to add one line to seek to the end before writing. 

    private async System.Threading.Tasks.Task AppendAsync(string filename, string text)
    {
        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
        using (Stream stream = await file.OpenStreamForWriteAsync())
        {
            stream.Seek(0, SeekOrigin.End);
            using (StreamWriter writer = new StreamWriter(stream))
            {
                await writer.WriteAsync(text);
                await writer.FlushAsync();
            }
        }
    }

    To call it, based on your original post:

    string dave = Environment.NewLine + T1.Text + "," + T2.Text + "," + T3.Text + "," + T4.Text + "," + T5.Text + "," + T6.Text;
    AppendAsync("sample.csv", dave);

    Sunday, January 26, 2014 3:20 AM
  • Hi there

    thanks for the response

    I entered the code. I had to add an Await and an Async to the button tap as it was showing an error

    When the button is clicked it seems to work as no errors are shown and it exits the save screen but I cant find the file on the phone where it is saving the data

    I tried putting a blank sample.csv file in the documents directory but it doesn't add the text to it

    Am I missing something. I have looked in all the directories on the phone and there is no file

    Mark

    Sunday, January 26, 2014 8:48 AM
  • I tested the code before posting. It works.

    Here's a complete example:

    1. Open a new Windows Phone project.
    2. Put this in MainPage.xaml (add the Button):
          <Grid x:Name="LayoutRoot" Background="Transparent">
              <Grid.RowDefinitions>
                  <RowDefinition Height="Auto"/>
                  <RowDefinition Height="*"/>
              </Grid.RowDefinitions>
      
              <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
                  <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
                  <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
                  <Button Content="append file" Tap="Button_Tap"/>
              </StackPanel>
          </Grid>
    3. Put this in MainPage.xaml.cs:
      using System.Threading.Tasks;
      using Windows.Storage;
      using System.IO;
      
      
      ...
      
      
          public partial class MainPage : PhoneApplicationPage
          {
              int index = 1;
      
              public MainPage()
              {
                  InitializeComponent();
              }
      
              private async void Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
              {
                  string dave = Environment.NewLine + "dave " + index++;
                  await AppendAsync("sample.csv", dave);
              }
      
              private async Task AppendAsync(string filename, string text)
              {
                  StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
                  using (Stream stream = await file.OpenStreamForWriteAsync())
                  {
                      stream.Seek(0, SeekOrigin.End);
                      using (StreamWriter writer = new StreamWriter(stream))
                      {
                          await writer.WriteAsync(text);
                          await writer.FlushAsync();
                      }
                  }
              }
          }
    4. Run the app and tap the button 3 times.
    5. Open an isolated storage explorer tool. In the top level of isolated storage, you will find a file named sample.csv with 3 lines:
      dave 1
      dave 2
      dave 3


    Richard Woo
    • Marked as answer by wambaugh1 Monday, January 27, 2014 6:12 AM
    Sunday, January 26, 2014 11:08 AM
  • hi richard

    Well I really dont know what I am doin wrong

    I have entered your code into a new project run it and it all seems to work but I cant find the file it makes

    i have downloaded three different file managers from windows store and looked at the whole contents from my PC over usb and there is no file called sample.csv anywhere

    Really don't know whats going wrong

    I need some way of saving multiple strings from my app so at a later date i can retrieve and send them via email

    any more ideas where im going wrong

    Mark

    Sunday, January 26, 2014 3:42 PM
  • You're trying to find the file on your PC? It's written to the app's isolated storage on the phone.

    The Isolated Storage Explorer tool that comes with the phone SDK is described here:
    http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh286408(v=vs.105).aspx
    (look at the bottom of the page for links to some 3rd party tools that are easier to use)

    Sunday, January 26, 2014 4:51 PM
  • Hi 

    Well that's a backwards step its like using DOS all over again I wasn't looking on the PC i was looking at Windows phone via a USB cable in file explorer just like every other phone does

    It was not showing anywhere when I looked on the phone

    It was saving it. My original code was saving it as well

    Used Windows phone Power Tools and it was there. Dont know why you cant see it in windows file explorer 

    Just need to reverse it now so that I can read all the lines of the file into one string so that I can send it in an email

    I will try and work it out I hope I can ask for your help if I cant Your were very helpful

    Mark


    • Edited by wambaugh1 Sunday, January 26, 2014 6:53 PM
    Sunday, January 26, 2014 6:45 PM
  • Dont know why you cant see it in windows file explorer
    Isolated storage is normally private, secured data accessible only by the phone app. These are developer tools that only work on a developer unlocked phone (or emulator), and only for a developer app you deployed through Visual Studio or xap deployment tool. You cannot examine the isolated storage of an app installed from the Store. Only that app can access its own isolated storage.
    Sunday, January 26, 2014 7:30 PM
  • Thanks for the explanation hopefully they will unify this in coming upgrades

    I have managed to read the file and put it in a string and send it as an email

    is there a way of on a button click clearing the contents of sample.csv or deleting it so that a new one is created

    Mark


    Sunday, January 26, 2014 10:47 PM
  • There must be an API to delete a file. Do a web search or look it up the documentation.

    In my example code, append or overwrite the file by executing the Seek statement or not. You can add a boolean argument to the method so that the caller can select to do one or the other.

    Monday, January 27, 2014 12:47 AM
  • Thank you for your help

         IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                storage.DeleteFile("sample.csv");

    This deletes the file

    Mark

    Monday, January 27, 2014 6:12 AM