Search code examples
c#windows-phonewin-universal-appwindows-10-mobile

UWP: byte[] to file


I have a byte[] and I want to store it into a file. This is my code:

using System.Runtime.InteropServices.WindowsRuntime;

StorageFolder folder = await GetStorageFolderFromFilePath(filePath);
StorageFile file = await folder.CreateFileAsync(Path.GetFileName(filePath), CreationCollisionOption.ReplaceExisting);

using (Stream stream = await file.OpenStreamForWriteAsync())
{
    IBuffer buffer = byteArray.AsBuffer();
    await FileIO.WriteBufferAsync(file, buffer);
}

A file is created but the file is empty. What am I doing wrong?


Solution

  • Why did you do not use FileIO.WriteBytesAsync method?

    public static IAsyncAction WriteBytesAsync(IStorageFile file, System.Byte[] buffer);
    

    You can do it in one line code:

    await FileIO.WriteBytesAsync(storageFile, byteArray);