TOpenTextFileDialog (C++)
Description
This example shows how to use the TOpenTextFileDialog and TSaveTextFileDialog to handle files with specific encodings.
Code
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
openTxtDlg = new TOpenTextFileDialog(this);
saveTxtDlg = new TSaveTextFileDialog(this);
// Create a new string list that holds encoding information.
TStrings* encodings = new TStringList();
// 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 (*.*)|*.*";
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (openTxtDlg->Execute(this->Handle))
{
// Setting the filename and encoding selected by the user
String filename = openTxtDlg->FileName;
int encIndex = openTxtDlg->EncodingIndex;
TEncoding* enc = dynamic_cast<TEncoding*>
(openTxtDlg->Encodings->Objects[encIndex]);
// Checking if the file exists
if (FileExists(filename))
{
// Display the contents in a memo based on the selected encoding.
Memo1->Lines->LoadFromFile(filename, enc);
}
else
{
MessageDlg("File does not exist", mtError,
TMsgDlgButtons() << mbOK, 0);
}
}
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{
if (saveTxtDlg->Execute(this->Handle))
{
// Setting the filename and encoding selected by the user
String filename = saveTxtDlg->FileName;
int encIndex = saveTxtDlg->EncodingIndex;
TEncoding* enc = dynamic_cast<TEncoding*>
(saveTxtDlg->Encodings->Objects[encIndex]);
// Checking if the file exists
if (FileExists(filename))
{
MessageDlg("File already exists", mtError,
TMsgDlgButtons() << mbOK, 0);
}
else
{
// Saves to file based on the selected encoding.
Memo1->Lines->SaveToFile(filename, enc);
}
}
}
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 )