我想在Delphi XE2中将文件读入到一个字节数组中。
这是我的当前代码:
function FileToBytes(const AName: string; var Bytes: TBytes): Boolean;
var
Ms: TMemoryStream;
begin
Result := False;
if not FileExists(AName) then
Exit;
Ms := TMemoryStream.Create;
try
Ms.LoadFromFile(AName);
if Ms.Size > 0 then
begin
Ms.Position := 0;
MS.ReadBuffer(Bytes[0], Ms.Size);
Result := True;
end;
finally
Ms.Free;
end;
end;
procedure runFile();
var
Bytes: TBytes;
OpFile: String;
begin
OpFile := 'C:\Users\Kenny\Documents\calc.exe';
Bytes := nil;
if FileToBytes(OpFile, Bytes) then
begin
//do someting with Bytes(array of Byte)
end;
end;
我在这一行遇到了错误:
MS.ReadBuffer(Bytes[0], Ms.Size);
错误信息如下:
如有帮助解决此问题的方法,请不吝赐教。访问地址 0x00000008 写入时发生访问冲突,错误地址为 0x00404727。
Bytes
是一个动态数组。你需要先使用SetLength
分配足够的空间。此外,如果你的需求非常简单,可以查看IOUtils.TFile.ReadAllBytes
。 - Andreas Rejbrand