[英]How to read file bytes from byte offset?
如果給我一個.cmp
文件和一個字節偏移量0x598
,我如何從這個偏移量讀取文件?
我當然可以像這樣讀取文件字節
byte[] fileBytes = File.ReadAllBytes("upgradefile.cmp");
但是我怎樣才能從字節偏移量0x598
讀取它
為了解釋更多,實際上從這個偏移量開始,我必須讀取實際數據,在這個字節偏移量之前它只是 header 數據,所以基本上我必須從那個偏移量讀取文件直到結束。
試試這樣的代碼:
using (BinaryReader reader = new BinaryReader(File.Open("upgradefile.cmp", FileMode.Open)))
{
long offset = 0x598;
if (reader.BaseStream.Length > offset)
{
reader.BaseStream.Seek(offset, SeekOrigin.Begin);
byte[]fileBytes = reader.ReadBytes((int) (reader.BaseStream.Length - offset));
}
}
如果您不熟悉 Streams、Linq 或其他什么,我為您提供了最簡單的解決方案:
將整個文件讀入 memory (希望你處理小文件):
byte[] fileBytes = File.ReadAllBytes("upgradefile.cmp");
計算給定偏移后數組中有多少字節:
long startOffset = 0x598; // this is just hexadecimal representation for human, it can be decimal or whatever
long howManyBytesToRead = fileBytes.Length - startOffset;
然后只需將數據復制到新數組:
byte[] newArray = new byte[howManyBytesToRead];
long pos = 0;
for (int i = startOffset; i < fileBytes.Length; i++)
{
newArray[pos] = fileBytes[i];
pos = pos + 1;
}
如果您了解它的工作原理,您可以查看 Microsoft 文檔中的Array.Copy
方法。
通過不使用 ReadAllBytes。
獲取 stream,移動到葯水,讀取 rest 文件。
您基本上抱怨一種允許單行讀取整個文件的便捷方法不是您想要的 - 忽略它只是一種便捷方法。 處理文件的正常方法是打開它們並使用 Stream。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.