6

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?

testing
  • 19,681
  • 50
  • 236
  • 417

3 Answers3

7

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);
Andrii Krupka
  • 4,276
  • 3
  • 20
  • 41
0

I think you'll find your solution here save stream to file in c# and winrt

basically, u need to read from your buffer.

Community
  • 1
  • 1
makro88
  • 102
  • 8
-1

maybe you should try this way:

System.IO.File.WriteAllBytes(path,bytes)

path - path to file, bytes - file