如何在Windows Phone 8中异步附加文件

时间:2013-02-24 23:04:50

标签: c# append windows-phone-8

我正在尝试附加到最新Windows Phone中的文件。问题是我试图异步做所有事情,我不知道该怎么做。

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

到目前为止我有这个,它写入文件很好,我可以稍后阅读它,但它写的是我拥有的而不是新的行。注释掉的行显示了如何在没有WP7流的情况下进行操作,但我无法使其工作(真实的是附加标志)并且真的应该使用新的WP8方法。

赞赏任何评论

3 个答案:

答案 0 :(得分:1)

更简单的方法:

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

答案 1 :(得分:0)

我使用此代码,适合我

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

        }

答案 2 :(得分:0)

我能够成功使用Oleh Nechytailo的建议(Stream.Seek())