TOpenTextFileDialog (Delphi)
Description
This example shows how to use the TOpenTextFileDialog and the TSaveTextFileDialog to handle files with specific encodings.
Code
procedure TForm1.Button1Click(Sender: TObject);
var
Encoding : TEncoding;
EncIndex : Integer;
Filename : String;
begin
if OpenTxtDlg.Execute(Self.Handle) then
begin
//Selecting the file name and the encoding
Filename := OpenTxtDlg.FileName;
EncIndex := OpenTxtDlg.EncodingIndex;
Encoding := OpenTxtDlg.Encodings.Objects[EncIndex] as TEncoding;
//Checking if the file exists
if FileExists(Filename) then
//Display the contents in a memo based on the selected encoding.
Memo1.Lines.LoadFromFile(FileName, Encoding)
else
raise Exception.Create('File does not exist.');
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Encoding : TEncoding;
EncIndex : Integer;
Filename : String;
begin
if SaveTxtDlg.Execute(Self.Handle) then
begin
//Selecting the file name and the encoding
Filename := SaveTxtDlg.FileName;
EncIndex := SaveTxtDlg.EncodingIndex;
Encoding := SaveTxtDlg.Encodings.Objects[EncIndex] as TEncoding;
//Checking if the file exists
if FileExists(Filename) then
raise Exception.Create('File already exists.')
else
//Save to file based on the selected encoding.
Memo1.Lines.LoadFromFile(FileName, Encoding);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
encodings : TStrings;
begin
OpenTxtDlg := TOpenTextFileDialog.Create(Self);
SaveTxtDlg := TSaveTextFileDialog.Create(Self);
// Create a new string list that holds encoding info.
encodings := TStringList.Create();
// Add some encodings to the list.
encodings.AddObject('ASCII', TEncoding.ASCII);
encodings.AddObject('UNICODE', TEncoding.Unicode);
encodings.AddObject('UTF8', TEncoding.UTF8);
OpenTxtDlg.Encodings.Assign(encodings);
SaveTxtDlg.Encodings.Assign(encodings);
OpenTxtDlg.Filter := 'Text files (*.txt)|*.TXT|XML files (*.xml)|*.XML|Any file (*.*)|*.*';
SaveTxtDlg.Filter := 'Text files (*.txt)|*.TXT|XML files (*.xml)|*.XML|Any file (*.*)|*.*';
end;
Uses
- Vcl.ExtDlgs.TOpenTextFileDialog ( fr | de | ja )
- Vcl.ExtDlgs.TSaveTextFileDialog ( fr | de | ja )
- Vcl.ExtDlgs.TOpenTextFileDialog.Encodings ( fr | de | ja )
- Vcl.ExtDlgs.TOpenTextFileDialog.EncodingIndex ( fr | de | ja )
- System.Classes.TStrings.LoadFromFile ( fr | de | ja )