Thema: Delphi File Types Detection

Einzelnen Beitrag anzeigen

mohfa

Registriert seit: 11. Feb 2007
97 Beiträge
 
Delphi 7 Enterprise
 
#1

File Types Detection

  Alt 8. Mai 2009, 08:00
To detect What a File ( Plain Text Files for Example)Type and Encoding I use the Following .

Is this Function Correct ? any other improvements .

Delphi-Quellcode:
Type
  TTxtFileType = (txTxtOrBin{Default},
    txUTF8,
    txUNICODE,
    txUNIBIG
  );

  TTxtFileSign = record
     Code : TTxtFileType;
     Sign : LongWord;
     Mask : LongWord;
     end;

     const
  TxtSignsCount = 3;
  TxtSign_UTF8 : TTxtFileSign = (Code: txUTF8; Sign:$00BFBBEF; Mask: $00FFFFFF);
  TxtSign_UNICODE : TTxtFileSign = (Code: txUNICODE; Sign:$0000FEFF; Mask: $FF00FFFF);
  TxtSign_UNIBIG : TTxtFileSign = (Code: txUNIBIG; Sign:$0000FFFE; Mask: $00FFFFFF);

var
TxtFileSigns : array[0..TxtSignsCount-1] of TTxtFileSign;

type
TForm1 = class(TForm)
    Button1: TButton;
    op: TOpenDialog;
    Label1: TLabel;
    Label2: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}


function TypeOfTextfile(const filename: string): TTxtFileType;
var
  Flux : TFileStream;
  Sign : LongWord;
  N : integer;
begin

  Flux := TFileStream.Create(FileName, fmOpenRead);
  try
    Flux.Read(Sign, 4);
  finally
    Flux.Free;
  end;
 {# Default # }
  result := txTxtOrBin;

  for N := 0 to High(TxtFileSigns) do
  begin

    if (Sign and TxtFileSigns[N].Mask) = TxtFileSigns[N].Sign then
    begin
      result := TxtFileSigns[N].Code;
      break;
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
if not op.Execute then exit;
Case TypeOfTextfile(op.FileName) of
txTxtOrBin:Label2.Caption:='TxtOrBin';
txUTF8:Label2.Caption:='UTF8';
txUNICODE:Label2.Caption:='UNICODE';
txUNIBIG:Label2.Caption:='UNIBIG';
end;
end;

end.
Angehängte Dateien
Dateityp: zip file_type_detect_103.zip (4,1 KB, 2x aufgerufen)
  Mit Zitat antworten Zitat