SQL Server: How to find all localdb instance names

前端 未结 4 1870
遥遥无期
遥遥无期 2020-12-04 19:26

I have two versions (2012, 2014) of SQL Server Express LocalDB installed in my system.

How can I find all existing LocalDB instance names?

I

4条回答
  •  时光取名叫无心
    2020-12-04 19:51

    Here is the method i am using to get all instances from command line -

        internal static List GetLocalDBInstances()
        {
            // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/C sqllocaldb info";
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            string sOutput = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
    
            //If LocalDb is not installed then it will return that 'sqllocaldb' is not recognized as an internal or external command operable program or batch file.
            if (sOutput == null || sOutput.Trim().Length == 0 || sOutput.Contains("not recognized"))
                return null;
            string[] instances = sOutput.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            List lstInstances = new List();
            foreach (var item in instances)
            {
                if (item.Trim().Length > 0)
                    lstInstances.Add(item);
            }
            return lstInstances;
        }
    

提交回复
热议问题