我想写一个来自IRandomAccessStream的文件

时间:2017-12-14 19:50:22

标签: c# uwp

这是我的代码:

                    using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                    {
                        //Irrelevant
                        BitmapImage bitmapImage = new BitmapImage();
                        await bitmapImage.SetSourceAsync(fileStream);
                        myImage.Source = bitmapImage;

                        //Relevant again
                        Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                        StorageFolder fol = await localFolder.GetFolderAsync("this");
                        StorageFile canvasFile = await fol.CreateFileAsync("background.png", CreationCollisionOption.ReplaceExisting);

                        using (var entryStream = await canvasFile.OpenStreamForWriteAsync())
                        {
                            await fileStream.AsStreamForRead().CopyToAsync(entryStream);
                        }
                    }

文件已创建,但大小为0位且非常空。任何想法可能会出错?

1 个答案:

答案 0 :(得分:0)

如果您要将IRandomAccessStream写入文件,则需要将IRandomAccessStream转换为IInputStream,然后使用DataReaderIInputStream获取缓冲区。有关更多详细信息,请参阅以下代码。

using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
    Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    StorageFolder fol = await localFolder.CreateFolderAsync("this", CreationCollisionOption.OpenIfExists);
    StorageFile canvasFile = await fol.CreateFileAsync("background.png", CreationCollisionOption.ReplaceExisting);
    using (var reader = new DataReader(fileStream.GetInputStreamAt(0)))
    {
        await reader.LoadAsync((uint)fileStream.Size);
        var buffer = new byte[(int)fileStream.Size];
        reader.ReadBytes(buffer);
        await Windows.Storage.FileIO.WriteBytesAsync(canvasFile, buffer);
    }
}