示例#1
0
        public static bool CreateDatabase()
        {
            bool Successful = false;

            using (new Impersonator()) {
                using (SqlConnection conn = DataSource.ConnMaster()) {
                    try {
                        //string X = conn.ConnectionString;

                        //conn.ConnectionString = X.Replace("catalog=" + DataSource.DB_CATALOG, "catalog=MASTER");

                        string sql = string.Empty;
                        sql = string.Format("IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = N'{0}') CREATE DATABASE [{0}]", DataSource.DB_CATALOG);
                        using (SqlCommand cmd = new SqlCommand(sql, conn)) {
                            if (conn.State != ConnectionState.Open)
                            {
                                conn.Open();
                            }
                            cmd.ExecuteNonQuery();

                            DateTime delay = DateTime.Now.AddSeconds(20);
                            //delay for database to be ready (up to 20 seconds)
                            do
                            {
                            } while (!DatabaseExists() && delay > DateTime.Now);
                            Successful = DatabaseExists();
                        }
                    } catch (Exception ex) {
                        Error.WriteError(ex);
                    }
                }
            }
            return(Successful);
        }