I need to read the content of an unknown type and size file and temporary save it (in some kind of variable) so I use it later for transferring through serial port. As far as I understand, TFileStream is the right approach.
I did try implementing the following tutorial from http://docwiki.embarcadero.com/CodeExamples/Tokyo/en/TReader_(Delphi)
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Utils;
type
TForm1 = class(TForm)
procedure OnCreate(Sender: TObject);
private
selectedFile: string;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.OnCreate(Sender: TObject);
function ReadFileContent(fileName: String): String;
var
FileStream: TFileStream;
Reader: TReader;
tByte :byte;
begin
FileStream := TFileStream.Create(fileName, fmOpenRead);
Reader := TReader.Create(FileStream, $FF);
Reader.ReadListBegin; //I get 'Invalid property Value' error
//in this line raised from the Reader object
while not Reader.EndOfList do
begin
Reader.ReadVar(tByte, 1);
end;
Reader.ReadListEnd;
Reader.Destroy;
FileStream.Destroy;
end;
var
dlg: TOpenDialog;
begin
selectedFile := '';
dlg := TOpenDialog.Create(nil);
try
dlg.InitialDir := '.\';
dlg.Filter := 'All files (*.*)|*.*';
if dlg.Execute(Handle) then
selectedFile := dlg.FileName;
finally
dlg.Free;
end;
if selectedFile <> '' then
ReadFileContent(selectedFile);
end;
end.
Is there anything else I need to set for the Reader object to work properly or I should use a different approach?
I need to read the content of an unknown type and size file and save it into a string.
Since you want to save it in a string, either
Assuming the first option, you can simply do
MyStringVariable := TFile.ReadAllText('C:\myfile.txt');
(uses IOUtils
).
There is also an overload of ReadAllText
that you can use to specify the encoding (e.g., UTF-8 or UTF-16LE).
Update. The question was edited and now reads
I need to read the content of an unknown type and size file and save it.
Do you simply want to copy a file? If so, you can use any of the file-copying methods that are available, such as the CopyFile
Win32 function, TFile.Copy
from IOUtils, and many more.
Or do you want to obtain the bytes of the file so you can process it in your application? If so, my original answer is close to what you need. Just use ReadAllBytes
instead of ReadAllText
:
MyDynamicByteArray := TFile.ReadAllBytes('C:\logo.bmp');
where MyDynamicByteArray
is a dynamic array of bytes (TArray<Byte>
, that is, array of byte
).