15 agosto 2009

Parsing a Delphi DFM File

Some time ago a friend asked me to help him to parse a DFM file into .NET objects. We tried to find something in the web that does the job but no success, so I accepted the challenge and wrote the parser he needed.

If for some reason you need a DFM parser, or just for curiosity, you can download it from here.

Here is an example of how to use it:

class Program { 
    static void Main(string[] args) { 
        var fileName = @"c:\Unit1.dfm"; 
        var dfmParser = new DfmParser(fileName); 
        dfmParser.ReadFile(); 
        foreach (var node in dfmParser.Nodes) { 
            if (node.PropertyType == "string") { 
                node.PropertyValue = "'Hello World!';"; 
            } 
        } 
        dfmParser.SaveFile(); 
    } 
}

The example above loads this file:

object Form1: TForm1
  Left = 0
  Top = 0
  object Label1: TLabel
    Left = 8
    Top = 40
    Caption = 'Label1';
  end
  object Label2: TLabel
    Left = 48
    Top = 40
    Caption = 'Label1';
  end
end

And rewrites like this:

object Form1: TForm1
  Left = 0
  Top = 0
  object Label1: TLabel
    Left = 8
    Top = 40
    Caption = 'Hello World!';
  end
  object Label2: TLabel
    Left = 48
    Top = 40
    Caption = 'Hello World!';
  end
end

If you find some use for this, enjoy :)

4 comentários:

  1. would you have this in a delphi code
    Thanks
    Philippe Watel
    philippe@triaina.com

    ResponderExcluir
  2. Just wanted to send a huge "THANK YOU", you saved me a lot of time

    ResponderExcluir
  3. Thank you much for this!
    Two bugs:
    1. Does not recognize Boolean (easy to repair).
    2. Exception("Index out of range") on more complicated object property, for example:
    ...
    Buttons = <
    item
    Default = True
    Glyph.Data = {
    D6000000...
    ...

    ResponderExcluir