Friday, November 4, 2011

Reading COM TypeLib GUID at Runtime

/*
* Every need to read a type library dll to update other reference files. This is often a requirment when working with languages
* that don't control the GUID or you just want to create a generic process. The example below can easily be turned into a console app
* that takes the DLL and Replacement file as command arguments. I'm using Visual Studio 2010.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using TYPELIBATTR = System.Runtime.InteropServices.ComTypes.TYPELIBATTR;

namespace GUIDReader
{

class Program

{

[
DllImport("oleaut32.dll", CharSet = CharSet.Unicode, PreserveSig = false)] static extern UCOMITypeLib LoadTypeLib(string szFile);

const string mydll = @"D:\mydll.dll";
const string globalasa = @"D:\global.asa";

static void Main(string[] args)
{

   
TYPELIBATTR tlibvalue = new TYPELIBATTR();
    IntPtr ptr;
    LoadTypeLib(imASPdll).GetLibAttr(out ptr);
    tlibvalue = (TYPELIBATTR)Marshal.PtrToStructure(ptr, typeof(TYPELIBATTR));
    var guidstr = tlibvalue.guid.ToString();
    Console.WriteLine(guidstr);

    StreamReader reader = new StreamReader(globalasa);
    string contents = reader.ReadToEnd();
    reader.Close();

    
var newvalue = "NAME=\"NAMEOFLIB\" UUID=\"{" + guidstr.ToUpper() + "\"}";
    var newText = Regex.Replace(contents, @"NAME=""NAMEOFLIB"" UUID=""{.*}""", newvalue);

    StreamWriter writer = new StreamWriter(globalasa);
    writer.Write(newText);
                writer.Close();

}

}

}

No comments: