从字节数组中删除范围

时间:2012-07-08 14:01:33

标签: c# bytearray byte

我在byte[]中有一个文件,我需要在每0x1000个偏移处删除x个字节(我有一个偏移列表)。我有一些代码要做,但我想知道是否有更好的方法来做到这一点;

private byte[] RemoveHashBlocks(byte[] fileArray, STFSExplorer stfs)
{
    long startOffset = StartingOffset;
    long endOffset = StartingOffset + Size;

    List<long> hashBlockOffsets = new List<long>();
    foreach (xBlockEntry block in stfs._stfsBlockEntry) 
        if (block.IsHashBlock && (block.BlockOffset >= startOffset && block.BlockOffset <= endOffset))
            hashBlockOffsets.Add(block.BlockOffset - (hashBlockOffsets.Count * 0x1000));

    byte[] newFileAray = new byte[fileArray.Length - (hashBlockOffsets.Count * 0x1000)];

    for (int offset = 0; offset < fileArray.Length; offset++)
        if (hashBlockOffsets[0] == offset)
        {
            offset += 0x1000;
            hashBlockOffsets.RemoveAt(0);
        }
        else
            newFileAray[offset] = fileArray[offset];

    return newFileAray;
}

1 个答案:

答案 0 :(得分:0)

private byte[] RemoveHashBlocks(byte[] fileArray, STFSExplorer stfs)
{
    long startOffset = StartingOffset;
    long size = Size;

    MemoryStream ms = new MemoryStream();
    long lastBlockEnd = 0;

    foreach (xBlockEntry block in stfs._stfsBlockEntry)
    {
        if (block.IsHashBlock)
        {
            long offset = block.BlockOffset - startOffset;
            if (offset + 0x1000 > 0 && offset < size)
            {
                if (offset > lastBlockEnd)
                {
                    ms.Write(fileArray, (int) lastBlockEnd,
                            (int) (offset - lastBlockEnd));
                }
                lastBlockEnd = offset + 0x1000;
            }
        }
    }

    if (lastBlockEnd < size)
    {
        ms.Write(fileArray, (int) lastBlockEnd, (int) (size - lastBlockEnd));
    }

    return ms.ToArray();
}

这假定stfs._stfsBlockEntryBlockOffset排序。