patterncsharpMinor
Get ProductCode from MSI File using DTF in C#
Viewed 0 times
filedtfgetusingmsifromproductcode
Problem
I've created this function to grab the MSI ProductCode from the MSI file itself. i couldn't find any native method for it. So I've implemented it the following way:
Would you do it any different?
Thanks.
public static string GetMSIProductCode(string msiFile)
{
string _result = null;
string productCodeQuery = "SELECT * FROM Property WHERE Property = 'ProductCode'";
Session product = Installer.OpenPackage(msiFile, true);
Database msiDB = product.Database;
View msiView = msiDB.OpenView(productCodeQuery);
msiView.Execute();
Record _record = msiView.Fetch();
_result = _record.GetString(2);
msiView.Close();
msiDB.Dispose();
return _result;
}Would you do it any different?
Thanks.
Solution
- Almost all objects you work with here are disposable so wrapping them with the
usingwould be a good start.
- The
msiDBvariable is not necessary.
- It is not necessary now to define the
resultabove the query. Variables should be defined as close to their usage as possible.
- We use the
_usually only for private fields not for local variables.
- You might consider the implicit type
var. It would make your code less verbose.
After applaying this we get:
public static string GetMSIProductCode(string msiFile)
{
var productCodeQuery = "SELECT * FROM Property WHERE Property = 'ProductCode'";
using(var product = Installer.OpenPackage(msiFile, true))
using(var msiView = product.Database.OpenView(productCodeQuery))
{
msiView.Execute();
using (var record = msiView.Fetch())
{
return record.GetString(2);
}
}
}Code Snippets
public static string GetMSIProductCode(string msiFile)
{
var productCodeQuery = "SELECT * FROM Property WHERE Property = 'ProductCode'";
using(var product = Installer.OpenPackage(msiFile, true))
using(var msiView = product.Database.OpenView(productCodeQuery))
{
msiView.Execute();
using (var record = msiView.Fetch())
{
return record.GetString(2);
}
}
}Context
StackExchange Code Review Q#143304, answer score: 2
Revisions (0)
No revisions yet.