Windows RT IRandomAccessStream 接口会在读过文件结尾时报告无效位置

Windows 运行时 IRandomAccessStream 接口会在读过文件结尾时报告无效位置

将 Windows 随机访问流 (IRandomAccessStream) 转换为托管流时,托管流将默认使用一个缓冲区。当文件中的最后一个字节填充到缓冲区中时,该缓冲区会读过文件结尾并报告位置不正确。此问题影响使用该位置的所有代码;例如,当您使用 System.IO.Compression.ZipArchive 类从 Windows 运行时流读取数据时,就会出现这种情况。

 

问题发生位置示例:

       

   Windows.Storage.Pickers.FileOpenPicker fop = new Windows.Storage.Pickers.FileOpenPicker();

   fop.FileTypeFilter.Add(".zip");

  

   StorageFile file = await fop.PickSingleFileAsync();

   using (System.IO.Stream s = await file.OpenStreamForReadAsync())

   {

      using (var za = new System.IO.Compression.ZipArchive(s))

      {

      foreach (var entry in za.Entries) // Fails here....            // Do something here

       {

         }

      }

   }

解决此问题的方法:

使用长度为零的缓冲区打开流。调用 file.OpenReadAsync() 而非 file.OpenStreamForReadAsync() 方法,然后对生成的 Windows 运行时流调用 AsStreamForRead(0)。

 

例如:

   using (var ws = await file.OpenReadAsync())

   {

      using (var s = ws.AsStreamForRead(0))

      {

         using (var za = new System.IO.Compression.ZipArchive(s)) // This will now work correctly.

         {

            // Do something here

         }

      }

   }

posted on 2012-06-03 09:25  On the Way  阅读(332)  评论(0编辑  收藏  举报

导航