AssetManager.Open 不支持 Stream.Seek?

问题描述

我目前正在尝试将基于 Windows 的游戏移植到 Android 上,但我一直无法在移动设备上加载文件系统。

我以各种存档格式存储我的文件,以避免通过创建自己的文件系统来处理不同的文件系统。然而,它依赖于 FileStreams 能够在档案中寻找数据的正确位置。

根据 Microsoft's docs,Access.Random 和 Access.Streaming 都应该支持在流中查找,但是无论我做什么,当我调用 Stream 时,使用 AssetManager.Open(string,Access) 创建的流都会崩溃. 从中寻找,给出 NotSupportedException。

这是我的错误,还是 SDK 上的已知缺陷,是否有解决方法

提前致谢。

编辑:根据要求,一个最小的可重现示例。

//class Game is a part of the MonoGame SDK. Game.Activity.Assets is a direct,unmodified version of
//Android.Content.Res.AssetManager,at least according to the docs.
//I believe the Seek function not being supported is a part of Xamarin's SDK,not Monogame's.
Stream stream = Game.Activity.Assets.Open(PathToArchive,Android.Content.Res.Access.Random);

stream.Seek(0,SeekOrigin.Begin); //causes exception regardless of seek value provided,and regardless of where the function is called.

解决方法

是的,来自 Assets.Open() 的流确实不支持 Seek 操作。您可以通过查看 CanSeek 属性来验证这一点。它会给您 false

所以你可以这样做:

Stream stream = Assets.Open(PathToArchive,Android.Content.Res.Access.Random);
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
ms.Seek(0,SeekOrigin.Begin);//use ms in place of stream