Delphi 2010: unable to find resource - EResNotFoun

2019-04-17 02:11发布

问题:

Based on examples at for instance here, here, and here, I'm trying to include SVN revision info in a project. The result of a svn info call is stored in rev.txt (it's a plain ansi file). My revinfo.rc looks like this:

REV_TEXT    TEXT    rev.txt

My project looks like this:

unit rev;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
type
  TForm2 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  end;
var
  Form2: TForm2;
implementation
{$R *.dfm}
{$R revinfo.res}
procedure TForm2.Button1Click(Sender: TObject);
var
  RS : TResourceStream;
  MyStr : AnsiString;
begin
  RS := TResourceStream.Create(hInstance, 'REV_TEXT', RT_RCDATA);
  SetLength(MyStr, RS.Size);
  RS.Read(MyStr[1], RS.Size);
  RS.Free;
  Memo1.Text := MyStr;
end;
end.

The project compiles, in other words, the resource file itself is located by the compiler (or perphaps it is the linker?). Anyway; when the statement TResourceStream.Create(hInstance, 'REV_TEXT', RT_RCDATA); is executed, I get an EResNotFound exception, complaining it can't find resource REV_TEXT. I can confirm that the resource file is compiled satisfactory, containing the content of the rev.txt text file. Are there anyone out there who're able to reproduce my troubles?

BTW: I've also tried to use the indexed version of the TResourceStream-constructor, but I don't know which index to use (tried 0, 1, and 2 to no avail).

I really appreciate your help! :)

回答1:

The problem in your code is the line:

 TResourceStream.Create(hInstance, 'REV_TEXT', RT_RCDATA);

You must call the TResourceStream.Create with the same type of the resource TEXT.

The following code should work:

var
  RS : TResourceStream;
  MyStr : AnsiString;
begin
  RS := TResourceStream.Create(hInstance, 'REV_TEXT', 'TEXT');
  try
   SetLength(MyStr, RS.Size);
   RS.Read(MyStr[1], RS.Size);
  finally
    RS.Free;
  end;
end;