C# loading binary files

孤者浪人 提交于 2019-12-04 20:13:36

1: For very small files File.ReadAllBytes will be fine.

2: For very big files and using .net 4.0 , you can make use MemoryMapped Files.

3: If Not using .net 4.0 than , reading chunks of data would be good choice

1) I'd use a resource file rather than storing it as lots of separate files.

2) you probably want to stream the data rather than read it all at once, in which case you can use a FileStream.

3): Use ReadAllBytes:

byte[] bytes = File.ReadAllBytes(path);

1: For small, File.ReadAllBytes

2: For big, Stream (FileStream) or a BinaryReader on a Stream - the purpose being to remove the need to allocate a massive buffer, by changing the code to read small chunks consecutively

3: Go back and find the expected size; default to worst-case (#2)

Also note that I'd try to minimise the siE in the first place, perhaps via the choice of data-format, or compression.

This sample is good for both - for large files you need buffered reads.

 public static byte[] ReadFile(string filePath)
 {
  byte[] buffer;
  FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  try
    {
     int length = (int)fileStream.Length;  // get file length
     buffer = new byte[1024];            // create buffer
     int count;                            // actual number of bytes read
     int sum = 0;                          // total number of bytes read

     // read until Read method returns 0 (end of the stream has been reached)
     while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
      sum += count;  // sum is a buffer offset for next reading
     }
     finally
     {
      fileStream.Close();
     }
      return buffer;
   }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!