C#加载二进制文件

请告诉我最佳/快速的方法:

1)将非常小的二进制文件加载到内存中。 例如图标;

2)加载/读取大小为512Mb +的非常大的二进制文件。

3)当你不想考虑大小/速度但必须做的事情时你的共同选择:将所有字节读入内存?

谢谢!!!

PS抱歉,这可能是一个微不足道的问题。 请不要关闭;)

PS2。 Java模拟问题的镜像 ;

1:对于非常小的文件File.ReadAllBytes会没问题。

2:对于非常大的文件并使用.net 4.0,您可以使用MemoryMapped Files。

3:如果不使用.net 4.0,读取数据块将是不错的选择

1)我使用资源文件而不是将其存储为许多单独的文件。

2)您可能希望流式传输数据而不是一次性读取所有数据,在这种情况下,您可以使用FileStream 。

3):使用ReadAllBytes :

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

1:对于小型File.ReadAllBytes

2:对于Big,Stream(FileStream)或Stream上的BinaryReader – 目的是通过更改代码连续读取小块来消除分配大量缓冲区的需要

3:回去找到预期的大小; 默认为最坏情况(#2)

另请注意,我首先尝试通过选择数据格式或压缩来最小化siE。

此示例适用于两者 – 对于大文件,您需要缓冲读取。

  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; }