function TForm1.ScanFileForString(aFile, SearchString:
String; IgnoreCase: Boolean=true;
MaxBytesScanned: Int64 = 2097152): Boolean;
const
MAX_BUFFER_SIZE = 20480;
//20 kb
var
Buffer:
String;
FS: TFileStream;
BytesRead: Integer;
i, match: Integer;
BufferSize, StrLength: Integer;
begin
Result := false;
If (SearchString = '
')
then exit;
If IgnoreCase
then SearchString := ANSIUppercase(SearchString);
//Datei öffnen... falls das nicht klappt gibts hier ne Exception
//daher die Funktion besser im try..except Schutzblock aufrufen!
FS := TFileStream.Create(aFile, fmOpenRead
or fmShareDenyWrite);
try
BufferSize := 0;
StrLength := Length(SearchString);
//Ermitteln wie groß der Puffer sein muss. Er soll ca. 20 kb groß sein,
//wenn nicht die ganze Datei reinpasst
If FS.Size <= MAX_BUFFER_SIZE
then
BufferSize := FS.Size
else
BufferSize := (MAX_BUFFER_SIZE
div StrLength) * StrLength;
SetLength(Buffer, BufferSize);
Repeat //Höchstens MaxBytesScanned Bytes untersuchen oder bis EOF
BytesRead := FS.
Read(Buffer[1], BufferSize);
If BytesRead = 0
then exit;
If IgnoreCase
then Buffer := ANSIUppercase(Buffer);
for i:=1
to BytesRead
do
begin
if Abbruch
then exit;
Application.ProcessMessages;
match := 0;
If (BufferSize-(i-1) >= StrLength)
then
while (Buffer[i+match] = SearchString[match+1])
do
begin
if Abbruch
then exit;
Application.ProcessMessages;
inc(match);
If match = StrLength
then
begin
Result := true;
//exit;
end;
end;
end;
Until (FS.Position >= MaxBytesScanned)
or (FS.Position = FS.Size);
finally
FS.Free;
SetLength(Buffer, 0);
end;
end;