Reputation: 83
How to get Product Version of Microsoft Sql Server from .mdf file Header using C# code.I have to open .mdf file and have to read product version from .mdf file header. product version means 11.0.2100.60 and 10.50.1600.0 like this.Not like this 8,9,10,11 and 661 ,705,611..
using (FileStream fs = File.OpenRead(mdffile))
{
using (BinaryReader br = new BinaryReader(fs))
{
br.ReadBytes(9 * 8192 + 96 + 4);
byte[] buffer = br.ReadBytes(2);
dbiVersion = buffer[0] + 256 * buffer[1];
}
fs.Close();
}
Upvotes: 3
Views: 669
Reputation: 754963
I use this code:
string mdfFileName = args[0];
if (!File.Exists(mdfFileName))
{
Console.WriteLine("ERROR: specified file does not exist!");
return;
}
NameValueCollection mdfFileVersions = ConfigurationManager.GetSection("MdfFileVersions") as NameValueCollection;
try
{
FileStream fs = new FileStream(mdfFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader reader = new BinaryReader(fs);
// skip the first 0x12064 bytes
reader.ReadBytes(0x12064);
// read two bytes
short fileVersion = reader.ReadInt16();
string sqlServerVersion = string.Empty;
if (mdfFileVersions != null)
{
sqlServerVersion = mdfFileVersions[fileVersion.ToString(CultureInfo.CurrentUICulture)];
if (string.IsNullOrEmpty(sqlServerVersion))
{
sqlServerVersion = "unknown version";
}
}
else
{
sqlServerVersion = "no version info available";
}
Console.WriteLine("Examined file: '{0}'", mdfFileName);
Console.WriteLine("File version : {0} ({1})", fileVersion, sqlServerVersion);
}
catch (Exception exc)
{
Console.WriteLine("ERROR: cannot open specified MDF file");
Console.WriteLine("\t{0}: {1}", exc.GetType().FullName, exc.Message);
}
and I have defined the file versions to look for in my app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MdfFileVersions" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<MdfFileVersions>
<add key="515" value="SQL Server 7" />
<add key="539" value="SQL Server 2000" />
<add key="616" value="SQL Server 2005 (up to SP1)" />
<add key="612" value="SQL Server 2005 (SP2 and newer)" />
<add key="655" value="SQL Server 2008 (up to SP1)" />
<add key="661" value="SQL Server 2008 R2" />
<add key="705" value="SQL Server 2012 RC0" />
<add key="706" value="SQL Server 2012" />
<add key="782" value="SQL Server 2014" />
</MdfFileVersions>
</configuration>
This makes it easily extensible - once newer versions come out, just add another entry in your config file, and your done!
Upvotes: 1