Breadbin
Breadbin

Reputation: 419

How to append a file, asynchronously in Windows Phone 8

I'm trying to append to a file in the latest Windows Phone. The problem is i'm trying to do everything asynchronously and i'm not sure how to do it.

    private async void writeResult(double lat, double lng)
    {

        StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        StorageFile storageFile = await localFolder.CreateFileAsync("result.txt", CreationCollisionOption.OpenIfExists);
        Stream writeStream = await storageFile.OpenStreamForWriteAsync();
        using (StreamWriter writer = new StreamWriter(writeStream))
        //using (StreamWriter sw = new StreamWriter("result.txt", true))
        {
            {
                await writer.WriteLineAsync(lat + "," + lng);
                //await sw.WriteLineAsync(lat + "," + lng);
                writer.Close();
                //sw.Close();
            }
        }
    }

I have this so far, which writes to the file fine and I can read it later on much the same, however it writes over what I have instead of on a new line. The commented out lines show how to go about without the stream in WP7, but I can't get that to work either (the true is is the append flag) and really should be utilizing the new WP8 methods anyway.

Any comments appreciated

Upvotes: 3

Views: 2343

Answers (3)

Tonatio
Tonatio

Reputation: 4208

Easier way:

await Windows.Storage.FileIO.AppendTextAsync(storageFile, "Hello");

Upvotes: 1

Breadbin
Breadbin

Reputation: 419

I was able to use the suggestion ( Stream.Seek() ) by Oleh Nechytailo successfully

Upvotes: 0

Bibaswann Bandyopadhyay
Bibaswann Bandyopadhyay

Reputation: 3557

I used this code, works for me

private async System.Threading.Tasks.Task WriteToFile()
        {
            // Get the text data from the textbox. 
            byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes("Some Data to write\n".ToCharArray());

            // Get the local folder.
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

            // Create a new folder name DataFolder.
            var dataFolder = await local.CreateFolderAsync("DataFolder",
                CreationCollisionOption.OpenIfExists);

            // Create a new file named DataFile.txt.
            var file = await dataFolder.CreateFileAsync("DataFile.txt",
            CreationCollisionOption.OpenIfExists);

            // Write the data from the textbox.
            using (var s = await file.OpenStreamForWriteAsync())
            {
                s.Seek(0, SeekOrigin.End);
                s.Write(fileBytes, 0, fileBytes.Length);
            }

        }

Upvotes: 0

Related Questions