简体   繁体   中英

Delphi: TFileStream & TStringList saving a blank text file

I'm a college student (UK) using delphi for my A2 Computing project. I'm really not very advanced so please bear with me! OK, so I'm using TStringList to save the contents of a TMemoBox to a textfile after encrypting it. However, this wasn't possible due to TStringList showing showing a linebreak after the message which messed up the encryption. I followed this article, which uses both TStringList and TFIleStream to remove this, but instead of giving me a full textfile, the result is empty. Please could you help save the data rather than not storing it at all? Thanks a lot. Here is a part of my procedure.

var
  EmailText : TStringList;
  FileStream : TFileStream;
begin
  FileName := 'email1.txt';
  EmailText := TStringList.Create;
  FileStream := TFileStream.Create(Filename, fmCreate);          

  EmailText.SaveToStream(FileStream, EmailText.Encoding);
  FileStream.Size := FileStream.Size - Length(System.sLineBreak);           
  EmailText.Add(EmailMessageMemo.Text);                            
  FileStream.Free;
  EmailText.Free;
EmailText := TStringList.Create; // new string list, empty
FileStream := TFileStream.Create(Filename, fmCreate); 
EmailText.SaveToStream(FileStream, EmailText.Encoding); 

So you have saved an empty string list to a file. So your file is consequently empty, because your string list is empty.

I guess you intended to add the content to the string list before you saved it.

EmailText := TStringList.Create;
EmailText.AddStrings(EmailMessageMemo.Lines);
FileStream := TFileStream.Create(Filename, fmCreate); 
EmailText.SaveToStream(FileStream, EmailText.Encoding); 

The extra string list is needless though. You can do it like this:

FileStream := TFileStream.Create(Filename, fmCreate); 
EmailMessageMemo.Lines.SaveToStream(FileStream, TEncoding.Default); 

I'd also like to point out, as I have done on so many other occasions, that encryption operates on binary rather than text. Of course, if you weren't trying to treat text as binary and vice versa, then you would not suffer from stray line break text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM