Read binary file in C# from specific position

蹲街弑〆低调 提交于 2021-01-21 10:20:58

问题


Is it possible to read a large binary file from a particular position?

I don't want to read the file from the beginning because I can calculate the start position and the length of the stream I need.


回答1:


        using (FileStream sr = File.OpenRead("someFile.dat"))
        {
            sr.Seek(100, SeekOrigin.Begin);
            int read = sr.ReadByte();
            //...
        }



回答2:


According to @shenhengbin answord.

Use BinaryReader.BaseStream.Seek.

using (BinaryReader b = new BinaryReader(File.Open("perls.bin", FileMode.Open)))                                                     
{
    int pos = 50000;
    int required = 2000;

    // Seek to our required position.
    b.BaseStream.Seek(pos, SeekOrigin.Begin);

    // Read the next 2000 bytes.
    byte[] by = b.ReadBytes(required);
}



回答3:


Well if you know streams, why not using (File)Stream.Seek(...) ?




回答4:


Of course it is possible.See this here.See the offset.you can read from the offset



来源:https://stackoverflow.com/questions/6674761/read-binary-file-in-c-sharp-from-specific-position

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