Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a string to a .txt file in Delphi?

Tags:

I need to make a program that generates a password that is saved in a text file format in a specific destination I set and the user needs to open the .txt to get the password to 'unlock' another program.

I have already got the code to generate the password in the string sPass and now I need to use the SaveToFile function to save it into the text file I created called Password.txt but I cannot find the general form to use the SaveTo File Function in Delphi and I do not know where to put the sPass and Password.txt in the function.

It should be something like : SaveToFile(...) but I do not know how to save sPass in Password.txt

Edit :

Just one more question, how do you delete what is previously stored in Password.txt before you add the string to it so that Password.txt is blank before the string is added ? Thanks

like image 341
Nyt Ryda Avatar asked Oct 13 '11 09:10

Nyt Ryda


People also ask

How do I create a new text file in Delphi?

Shortest answer possible: FileCreate('filename. txt');


2 Answers

The Modern Modern way is to use TFile.WriteAllText in IOUtils (Delphi 2010 and up)

procedure WriteAllText(const Path: string; const Contents: string); overload; static;

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

like image 166
awmross Avatar answered Sep 18 '22 15:09

awmross


The modern way is to create a stringlist and save that to file.

procedure MakeAStringlistAndSaveThat; var   MyText: TStringlist; begin   MyText:= TStringlist.create;   try     MyText.Add('line 1');     MyText.Add('line 2');     MyText.SaveToFile('c:\folder\filename.txt');   finally     MyText.Free   end; {try} end; 

Note that Delphi already has a related class that does everything you want: TInifile.
It stores values and keys in a key = 'value' format.

passwordlist:= TInifile.Create; try   passwordlist.LoadFromFile('c:\folder\passwords.txt');   //Add or replace a password for `user1`   passwordlist.WriteString('sectionname','user1','topsecretpassword');   passwordlist.SaveToFile('c:\folder\passwords.txt'); finally   passwordlist.Free; end; {try} 

Warning
Note that saving unecrypted passwords in a textfile is a security-leak. It's better to hash your passwords using a hashfunction, see: Password encryption in Delphi
For tips on how to save passwords in a secure way.

like image 33
Johan Avatar answered Sep 19 '22 15:09

Johan