Re:multiple RichEdit text to single file
Quote
Adam M wrote:
> Can anyone please suggest a solution to my problem; ie. a way to
> create a single file where multiple richedit formatted texts can be
> saved, and then loaded back into their respective richedits at a
> later time.
Sorry for the huge paste, but all those try...finally's are necessary to
make the compiler happy. You can leave them out if you want. OK, here goes:
// save the content of multiple richedit's to a file
procedure TForm1.SaveClick(Sender: TObject);
var
FileStream: TFileStream;
Writer: TWriter;
StringStream: TStringStream;
begin
FileStream := TFileStream.Create('text.dat', fmCreate);
try
Writer := TWriter.Create(FileStream, 4096);
try
StringStream := TStringStream.Create('');
try
RichEdit1.Lines.SaveToStream(StringStream);
Writer.WriteString(StringStream.DataString);
finally
StringStream.Free
end;
StringStream := TStringStream.Create('');
try
RichEdit2.Lines.SaveToStream(StringStream);
Writer.WriteString(StringStream.DataString);
finally
StringStream.Free;
end;
finally
Writer.Free;
end;
finally
FileStream.Free;
end;
end;
// and it's counterpart, loading the file into multiple richedit's
procedure TForm1.LoadClick(Sender: TObject);
var
FileStream: TFileStream;
Reader: TReader;
StringStream: TStringStream;
begin
FileStream := TFileStream.Create('text.dat', fmOpenRead);
try
Reader := TReader.Create(FileStream, 4096);
try
StringStream := TStringStream.Create(Reader.ReadString);
try
RichEdit1.Lines.LoadFromStream(StringStream);
finally
StringStream.Free;
end;
StringStream := TStringStream.Create(Reader.ReadString);
try
RichEdit2.Lines.LoadFromStream(StringStream);
finally
StringStream.Free;
end;
finally
Reader.Free;
end;
finally
FileStream.Free;
end;
end;
This is a much cleaner (ahum!) way of saving to a file. The advantage of
this method is that you don't have to fiddle with saving the length of the
text etc. Well, in fact the length is saved to the file through the TWriter
object. But you don't see it (and it's almost always a good thing(tm) to
keep things transparent). There is some optimalization (size! not speed)
possible by saving the contents of the richedit's in a loop though.
--
www.zenobits.com