Question

I've a C# 4.0 console application and a SQL Server 2008 database up and running on database server.

Does somebody know if there is a way to get the database properties (like "Database Read-Only" ) from the C# code?

My guess is it should be, but I was not able to find out the accurate solution.

Thanks in advance

Was it helpful?

Solution

There are at least two ways to do it. One is to use the Database Metadata tables the other to use SQL Management objects in both cases there's lot of data there so you really need to know what you want. For example this is how you would get the "Database Read-Only" property you mentioned.

Using a SqlCommand against the MetaData

using (SqlConnection cnn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;"))
{
   SqlCommand cmd = new SqlCommand("SELECT is_read_only FROM sys.filegroups",cnn);
   cnn.Open();
   var isReadOnly = cmd.ExecuteScalar();
   Console.WriteLine(isReadOnly );
}

Using SMO

using System;
using Microsoft.SqlServer.Management.Smo;

namespace SMO_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Server srv = new Server(); //Connection to the local SQL Server 

            Database db = srv.Databases["master"];
            foreach (FileGroup fg in db.FileGroups)
            {
                Console.WriteLine(fg.ReadOnly);

            }

        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top