Wednesday, May 8, 2013

How to access MSI database using C#

First create a console project.

Add following reference


Add following code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using WindowsInstaller;


namespace msiReadTest1
{
    [System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
    class Installer { }

    class Program
    {
        static void Main(string[] args)
        {
            WindowsInstaller.Installer ins = (WindowsInstaller.Installer)new Installer();
            string strFileMsi = @"C:\Users\kyadav.STC\Desktop\VitreaEnterpriseSuiteClient6.5.0.msi";
            Database db = ins.OpenDatabase(strFileMsi, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
           
            string sql = "Select `Property`.`Property` FROM `Property`";
            View vw = db.OpenView(sql);  // I'd like to pull from other tables besides Property as well
            vw.Execute(null);
            Record rcrd = vw.Fetch();
            while (rcrd != null)
            {
                Console.WriteLine(rcrd.get_StringData(1).Split('|')[0]);
                rcrd = vw.Fetch();
            }
            vw.Close();
            Console.ReadLine();
         
        }
    }
}