2007. március 17., szombat

How to retrieve rich text from a resource file and save it to disk


Problem/Question/Abstract:

How to retrieve rich text from a resource file and save it to disk

Answer:

These are the basic steps:

Create a resource file
Include it in your project
Load the file from the resource file into a TResourceStream
Create a TFileStream with the filename you want to write to
Use CopyFrom to get the data from the TResourceStream to the TFileStream
Free both the streams

The file is magically written to disk, without any need to call a write procedure or anything like that. It takes a file called 'test.rtf' from the resource file TEST.RES and saves it out to disk as 'test2.rtf' in the application folder:

{$R TEST.RES}

procedure TfrmMain.Button1Click(Sender: TObject);
var
  ResStream: TResourceStream
  MyFileStream: TFileStream;
begin
  try
    MyFileStream := TFileStream.Create(ExtractFilePath(Application.ExeName) +
      ' test2.rtf ', fmCreate or fmShareExclusive);
    ResStream := TResourceStream.CreateFromID(HInstance, 1, RT_RCDATA);
    MyFileStream.CopyFrom(ResStream, 0);
  finally
    MyFileStream.Free;
    ResStream.Free;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése