Mega Code Archive

 
Categories / Delphi / Files
 

Writing a file from a string

Title: Writing a file from a string Question: How can I save the contents of a string in a file? Answer: The following procedure "SaveFile" receives a file name as parameter and the string we want to save in it. If the file does not exist, it is created, and if it exists, its previous content is discarded. procedure SaveFile(const FileName: TFileName; const content: string); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmCreate); try Stream.Write(Pointer(content)^, Length(content)); except Stream.Free; raise; end; Stream.Free; end; Sample call: SaveFile('test.txt', 'ABC'); // Stores "ABC" in the file "test.txt"