Upgrade SQL CE Database from 3.1 to 3.5



var engine = new System.Data.SqlServerCe.SqlCeEngine(“Data Source=” + filename);


engine.EnsureVersion35(filename);


 


–HELPER CLASS—


    public static class SqlCeUpgrade


    {


        public static void EnsureVersion35(this SqlCeEngine engine, string filename)


        {


            try


            {


                SQLCEVersion fileversion = DetermineVersion(filename);


                if (fileversion == SQLCEVersion.SQLCE20)


                    throw new ApplicationException(“Unable to upgrade from 2.0 to 3.5”);


                if (SQLCEVersion.SQLCE35 > fileversion)


                {


                    engine.Upgrade();


                }


            }


            catch (Exception ex)


            {


                Console.WriteLine(ex.Message);


                throw;


            }


        }


        private enum SQLCEVersion


        {


            SQLCE20 = 0,


            SQLCE30 = 1,


            SQLCE35 = 2


        }


        private static SQLCEVersion DetermineVersion(string filename)


        {


            var versionDictionary = new Dictionary<int, SQLCEVersion>


            {


                { 0x73616261, SQLCEVersion.SQLCE20 },


                { 0x002dd714, SQLCEVersion.SQLCE30},


                { 0x00357b9d, SQLCEVersion.SQLCE35}


            };


            int versionLONGWORD = 0;


            try


            {


                using (var fs = new FileStream(filename, FileMode.Open))


                {


                    fs.Seek(16, SeekOrigin.Begin);


                    using (BinaryReader reader = new BinaryReader(fs))


                    {


                        versionLONGWORD = reader.ReadInt32();


                    }


                }


            }


            catch


            {


                throw;


            }


            if (versionDictionary.ContainsKey(versionLONGWORD))


            {


                return versionDictionary[versionLONGWORD];


            }


            else


            {


                throw new ApplicationException(“Unable to determine database file version”);


            }


        }


 


    }


 


 

Comments (1)

  1. Daniel says:

    I wonder if the second line of code in the calling method above needs to be changed.

    It reads:

    engine.EnsureVersion35(filename);

    Shouldn't it read:

    SqlCeUpgrade.EnsureVersion35(engine, filename);