Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在WinRT中逐块写入文件?_C#_Windows 8_Windows Runtime_File Transfer - Fatal编程技术网

C# 如何在WinRT中逐块写入文件?

C# 如何在WinRT中逐块写入文件?,c#,windows-8,windows-runtime,file-transfer,C#,Windows 8,Windows Runtime,File Transfer,我正在尝试将缓冲区数据写入文件。我在回调函数中连续接收缓冲区数据。我需要读取缓冲区并在接收时将其保存在文件中。这将重复,直到我得到完整的文件,我得到4k大小的数据块。但下面的代码要么抛出异常,要么输出文件损坏。请让我知道如何在winRT中执行此操作 StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(strFileName, Windows.Storage.Cre

我正在尝试将缓冲区数据写入文件。我在回调函数中连续接收缓冲区数据。我需要读取缓冲区并在接收时将其保存在文件中。这将重复,直到我得到完整的文件,我得到4k大小的数据块。但下面的代码要么抛出异常,要么输出文件损坏。请让我知道如何在winRT中执行此操作

StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(strFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);
public async void Receive(byte[] buffer)
{
  using (var ostream = await file.OpenStreamForWriteAsync())
  {
     await ostream.WriteAsync(buffer, 0, buffer.Length);
  }
}

问题在于
Receive
的签名。因为它是
void
,所以不需要等待它,您可以同时运行写入进程(这可能是导致异常和/或损坏数据的原因)

我建议改用这个:

StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(strFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);
public async Task Receive(byte[] buffer)
{
  using (var ostream = await file.OpenStreamForWriteAsync())
  {
     await ostream.WriteAsync(buffer, 0, buffer.Length);
  }
}
打电话给

await Receive(b);