根据文件头确认文件类型

function ExtractFileHead(Stream: TStream): string; overload;
var
  tmpPos: Longint;
  dwHead0, dwHead1: Word;
begin
  Result := '';
  if Assigned(Stream) then
  try
    tmpPos := Stream.Position;
    if Stream.Size > 2 then
    try
      Stream.Position := 0;
      Stream.ReadBuffer(dwHead0, 2);
      Stream.ReadBuffer(dwHead1, 2);
      case dwHead0 of
        $5C7B: Result := '.rtf';
        $4D42: Result := '.bmp';
        $D8FF: Result := '.jpg';
        $5089: Result := '.png';
        $4952: Result := '.avi';
        $4B50: Result := '.zip';
        $6152: Result := '.rar';
        $7A37: Result := '.7z';
        $5A4D: Result := '.exe';
        $0000:
          case dwHead1 of
            $BA01, $B301: Result := '.mpeg'
          end;
      end;
    except
      exit;
    end;
  finally
    if Assigned(Stream) then
      Stream.Position := tmpPos;
  end;
end;

function ExtractFileHead(FileName: string): string; overload;
var
  Stream: TFileStream;
begin
  Result := '';
  if FileExists(FileName) then
  try
    try
      Stream := TFileStream.Create(FileName, fmOpenRead);
      Result := ExtractFileHead(Stream);
    except
      Exit;
    end;
  finally
    if Assigned(Stream) then
      FreeAndNil(Stream)
  end;
end;

 

你可能感兴趣的:(delphi)