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

Nyt Ryda picture Nyt Ryda · Oct 13, 2011 · Viewed 67.7k times · Source

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

Answer

awmross picture awmross · Oct 14, 2011

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.