Search code examples
delphicharacter-encodingfile-encodings

Delphi stream saving explanation


There is this code block I used for a while.

Definitions:

type TItem = record
 Code          : string[255];
 Description   : string[255];
 Warning       : string[255];
 Fold          : integer;     //position where clamp to fold, 0 = flat, about 170 when needs to be folded
 PrintStrength : integer;     //put 0 if default to machine parameters, normally about 56
     PrintSpeed    : integer;     //put 0 if default to machine parameters, normally about 130
end;
var
  Item : TItem;
  LabelBitmap : TBitmap;

Code Block:

procedure DosyaYazdir(filename : string; Bitmap : Tbitmap);
var FileStream : TFileStream;
    siz: int64;
begin

  try
    FileStream := TFileStream.Create(filename, fmCreate);
    siz := SizeOf(Item);
    FileStream.Write(siz,SizeOf(siz));
    FileStream.Write(Item,siz);
    //Bitmap.SaveToStream(FileStream);
    form1.image2.picture.bitmap.SaveToStream(filestream);
    form1.Memo1.Lines.SaveToStream(FileStream,TEncoding.Unicode); 
    FileStream.free;
  except
    Application.MessageBox('Wrong file name','Kayıt Hatası :',MB_ICONERROR);
  end;
  form1.memo1.lines.clear;
end;

I call like this: (I don't do anything with LabelBitmap)

dosya:='C:\Custom_Etiket.itm';
DosyaYazdir(dosya,LabelBitmap);

Which saves the given strings (form1.memo1.Lines) into a file with given name. This was readymade I found on internet and now unfortunately I want to change my software to C#.

Since this was readymade, I don't really know what this code does. Because when I try to do in C#, I can not get the same output (with same encoding or whatsoever)

Here is the sample screenshot from the file it generates: (You can see the text between NULs but it has some kind of encoding) delphi generated file screenshot part

What does this Delphi Code block do? Or what should I do to get the same encoding?

//PS. Feel free to edit the title if it doesn't describe the situation well enough.


Solution

  • What does this Delphi Code block do?

    The Delphi code does the following:

    • Write a 64 bit integer to the file.
    • Write the binary representation of Item to the file. We don't know what Item is.
    • Write a bitmap to the file in bmp format.
    • Write a text file to the file using UTF-16LE encoding.

    This is a really poorly designed file. You really should be using JSON or XML or YAML or indeed any structured format for this data.