How to get Microsoft Sql Server product version from .mdf file Header using C # code
How to get Microsoft Sql Server product version from .mdf file Header using C # code. I need to open a .mdf file and read the product version from the .mdf file. product version means 11.0.2100.60 and 10.50.1600.0 like this. Dislike 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();
}
+3
source to share
1 answer
I am using 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 search in my file app.config
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 - as soon as newer versions are available, just add another entry to your config file and do it!
0
source to share