2012-07-08 162 views
0

我有一個文件在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

RemoveAt for List或數組重新定位它們。而不是從陣列中刪除某些東西來創建一個新的,只複製那些需要的值。 – 2012-07-08 14:07:19

+1

使用LINQ - 'array.Skip(0x1000).Take(N).ToArray();' - from:http://stackoverflow.com/questions/943635/c-sharp-arrays-getting-a-sub-array -from-AN-現有陣列 – Tisho 2012-07-08 14:11:32

回答

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排序。