开发者

TStringList load memorystream? <Delphi>

edited :

My file has several lines. I encrypt the file onto a new file. I want to store each line of decrypted file (=a stream) into StringList.

First, I have a file contain :

aa
bb
cc

I encrypt the file with this function :

procedure EnDecryptFile(pathin, pathout: string; Chave: Word) ;
 var
   InMS, OutMS: TMemoryStream;
   cnt: Integer;
   C: byte;
 begin
   InMS := TMemoryStream.Create;
   OutMS := TMemoryStream.Create;
   try
     InMS.LoadFromFile(pathin) ;
     InMS.Position := 0;
     for cnt := 0 to InMS.Size - 1 do
       begin
         InMS.Read(C, 1) ;
         C := (C xor not (ord(chave shr cnt))) ;
         OutMS.Write(C, 1) ;
       end;
     OutMS.SaveToFile(pathout) ;
   finally
     InMS.Free;
     OutMS.Free;
   end;
 end;

My purpose now is to store original value of each line into StringList. I don't want to store decrypted file into harddisk, so I use stream.

This is the function to decrypt the file into stream :

procedure Decry开发者_如何学PythonptFile(pathin: string; buff: TMemoryStream; Chave: Word);
var
  InMS: TMemoryStream;
  cnt: Integer;
  C: byte;
begin
  InMS := TMemoryStream.Create;
  try
    InMS.LoadFromFile(pathin);
    InMS.Position := 0;
    for cnt := 0 to InMS.Size - 1 do
    begin
      InMS.Read(C, 1);
      C := (C xor not(ord(Chave shr cnt)));
      buff.Write(C, 1);
    end;
    // buff.SaveToFile('c:\temp\dump.txt') ;
  finally
    InMS.free;
  end;
end;

--

 bbuffer := TMemoryStream.Create;
    try
      DecryptFile(path, bbuffer, 10); //  
      //ShowMessage(IntToStr(bbuffer.size)); // output : 1000
      bbuffer.Position := 0;
      SL := TStringList.Create; 
      try
        SL.LoadFromStream(bbuffer);
        for I := 0 to SL.Count - 1 do // SL.Count = 1
        begin;
        //add each line of orginal file into SL??
        end;
      finally
        SL.free;
      end;
    finally
      bbuffer.free;
    end;


Load from stream takes a TStream so you can give it a TFileStream as well as an TMemoryStream. The code you posted should work without any problems. What exactly does not work?

You might have to use

bbuffer.Position := 0;

to reset the position to the start of the stream before loading it into the string list.

EDIT: You write single bytes to a stream and then try to load a string list from it. That won't work. The stream is just a collection of bytes. How should the string list know where one string ends and the next one starts? TStringList.SaveToStream writes separator bytes to the stream so that it can parse the string list back. So, you could do your encryption on the string list and then write the whole string list to the stream, then read the stringlist and do the decryption on the string list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜