Composite Stream Wrapper providing partial MemoryStream and full original Stream

回眸只為那壹抹淺笑 提交于 2019-11-28 13:46:51

There isn't any reasonable way you can use a MemoryStream to work around the bug, you'll fall over on OutOfMemoryException first. Let's focus a bit on the bug, I'll simplify the code a bit to make it readable:

DistanceToMove = (offset & 0xffffffff00000000L) >> 32;
DistanceToMoveHigh = offset & 0xffffffffL;
SetFilePointer(this.m_handle, lDistanceToMove, ref lDistanceToMoveHigh, begin);

The Microsoft programmer accidentally swapped the low and high values. Well, so can you to undo the bug. Swap them yourself so the bug swaps them back the way you want it:

public static void SeekBugWorkaround(Stream stream, long offset, SeekOrigin origin) {
    ulong uoffset = (ulong)offset;
    ulong fix = ((uoffset & 0xffffffffL) << 32) | ((uoffset & 0xffffffff00000000L) >> 32);
    stream.Seek((long)fix, origin);
}

In case it needs to be said, it apparently does, you do have to count on Microsoft eventually fixing this bug. Hard to predict when so gamble on the next point release. There are some odds you can auto-detect this, albeit that it isn't obvious what Microsoft is going to do since this bug is so breaking. The return value of Seek() as well as the Position property return value suffer from the same bug. So seek to position 1 and verify that you get 1 back.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!