您是否正在寻找这个:
var bytes = File.ReadAllBytes(@"yourpathtofile");
或者更多类似的东西:
using (var filestream = File.Open(@"C:\apps\test.txt", FileMode.Open))
using (var binaryStream = new BinaryReader(filestream))
{
for (var i = 0; i < arraysize; i++)
{
Console.WriteLine(binaryStream.ReadInt32());
}
}
或者,一个带有单元测试的小例子:
用整数创建一个二进制文件...
[Test]
public void WriteToBinaryFile()
{
var ints = new[] {1, 2, 3, 4, 5, 6, 7};
using (var filestream = File.Create(@"c:\apps\test.bin"))
using (var binarystream = new BinaryWriter(filestream))
{
foreach (var i in ints)
{
binarystream.Write(i);
}
}
}
还有一个从二进制文件读取的小示例测试
[Test]
public void ReadFromBinaryFile()
{
// Approach one
using (var filestream = File.Open(@"C:\apps\test.bin", FileMode.Open))
using (var binaryStream = new BinaryReader(filestream))
{
var pos = 0;
var length = (int)binaryStream.BaseStream.Length;
while (pos < length)
{
var integerFromFile = binaryStream.ReadInt32();
pos += sizeof(int);
}
}
}
从二进制文件读取的另一种方法
[Test]
public void ReadFromBinaryFile2()
{
// Approach two
using (var filestream = File.Open(@"C:\apps\test.bin", FileMode.Open))
using (var binaryStream = new BinaryReader(filestream))
{
while (binaryStream.PeekChar() != -1)
{
var integerFromFile = binaryStream.ReadInt32();
}
}
}