目前,当我读取 15Mb 文件时,我的应用程序会占用大量内存。请注意,在主代码的末尾,我将插入数据库中的数据与文件中的原始数组进行比较。欢迎任何建议。
主要代码:
TestEntities entities = new TestEntities();
using (FileStream fileStream = new FileStream(fileName + ".exe", FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[fileStream.Length];
int numBytesToRead = (int) fileStream.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
int n = fileStream.Read(bytes, numBytesRead, numBytesToRead);
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
var query = bytes.Select((x, i) => new {Index = i, Value = x})
.GroupBy(x => x.Index/100)
.Select(x => x.Select(v => v.Value).ToList())
.ToList();
foreach (List<byte> list in query)
{
Binary binary = new Binary();
binary.Name = fileName + ".exe";
binary.Value = list.ToArray();
entities.AddToBinaries(binary);
}
entities.SaveChanges();
List<Binary> fileString = entities.Binaries.Where(b => b.Name == fileName + ".exe").ToList();
Byte[] final = ExtractArray(fileString);
if (Compare(bytes, final))
{
/// Some notification that was ok
}
}
比较方法:
public bool Compare(Byte[] array1,Byte[] array2)
{
bool isEqual = false;
if (array1.Count() == array2.Count())
{
for (int i = 0; i < array1.Count(); i++)
{
isEqual = array1[i] == array2[i];
if (!isEqual)
{
break;
}
}
}
return isEqual;
}
ExtractArray 方法:
public Byte[] ExtractArray(List<Binary> binaries )
{
List<Byte> finalArray = new List<Byte>();
foreach (Binary binary in binaries)
{
foreach (byte b in binary.Value)
{
finalArray.Add(b);
}
}
return finalArray.ToArray();
}