How to append a file, asynchronously in Windows Phone 8

耗尽温柔 提交于 2020-01-04 04:19:47

问题


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


回答1:


Easier way:

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



回答2:


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

        }



回答3:


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



来源:https://stackoverflow.com/questions/15057768/how-to-append-a-file-asynchronously-in-windows-phone-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!