UWP: byte[] 到文件

UWP: byte[] to file

我有一个 byte[],我想将它存储到一个文件中。这是我的代码:

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

文件已创建,但该文件为空。我做错了什么?

也许你应该试试这个方法:

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

path - 文件路径, 字节 - 文件

我想你会在这里找到你的解决方案save stream to file in c# and winrt

基本上,你需要从你的缓冲区中读取。

你为什么不使用 FileIO.WriteBytesAsync 方法?

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

一行代码即可完成:

await FileIO.WriteBytesAsync(storageFile, byteArray);