当前位置: 首页 > 编程语言 > C#

如何列出本机安装的SQLServer实例?(仅限本地)分享

时间:2023-04-11 10:34:12 C#

如何列出本地安装的SQLServer实例?(仅限本地)我想知道是否有办法列出安装在本地计算机上的SQLServer实例。SqlDataSourceEnumerator和EnumAvailableSqlServers没有这个技巧,因为我不需要本地网络上的实例。您可以使用localOnly=True调用EnumAvailableSQlServerspublicstaticDataTableEnumAvailableSqlServers(boollocalOnly)请参阅EnumAvailableSqlServers的MSDN文档MS建议不要直接访问Windows注册表,因为它们可以更改键/路径。但我同意SmoApplication.EnumAvailableSqlServers()和SqlDataSourceEnumerator.Instance不能在64位平台上提供实例。从Windows注册表获取数据,牢记x86和x64平台之间注册表访问的差异。64位版本的Windows将数据存储在系统注册表的不同部分,并将它们组合到视图中。所以使用RegistryView是必不可少的。使用Microsoft.Win32;RegistryViewregistryView=Environment.Is64BitOperatingSystem?RegistryView.Registry64:RegistryView.Registry32;使用(RegistryKeyhklm=RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,registryView)){RegistryKeyinstanceKey=hklm.OpenSubKey(@"SOFTWAREMicrosoftMicrosoftSQLServerInstanceNamesSQL",false);if(instanceKey!=null){foreach(varinstanceNameininstanceKey.GetValueNames()){Console.WriteLine(Environment.MachineName+@""+instanceName);}}}如果您在64位操作系统上寻找32位实例(非常奇怪,但可能),您需要查看:HKEY_LOCAL_MACHINESOFTWAREWow6432NodeMicrosoftMicrosoftSQLServerSqlDataSourceEnumeratorEnumeratorinstance=SqlDataSourceEnumeratorinstance=SSystem.Data.DataTable表=instance.GetDataSources();foreach(System.Data.DataRowrowintable.Rows){if(row["ServerName"]!=DBNull.Value&&Environment.MachineName.Equals(row["ServerName"].ToString())){stringitem=字符串.空;item=row["ServerName"].ToString();if(row["InstanceName"]!=DBNull.Value||!string.IsNullOrEmpty(Convert.ToString(row["InstanceName"]).Trim())){item+=@""+Convert.ToString(row["InstanceName"]).Trim();}listview1.Items.Add(项目);}}您可以使用注册表获取本地系统中的SQLServer实例名称privatevoidLoadRegKey(){RegistryKeykey=Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftMicrosoftSQLServer实例名称");foreach(stringskinkey.GetSubKeyNames()){RegistryKeyrkey=key.OpenSubKey(sk);foreach(stringsinrkey.GetValueNames()){MessageBox.Show("Sql实例名:"+s);}}}结合几种方法:以上是C#学习教程:如何列出本地计算机上安装的SQLServer实例?(仅限本地)所有分享的内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——usingMicrosoft.SqlServer.Management.Smo;使用Microsoft.SqlServer.Management.Smo.Wmi使用System.Collections.Generic;使用系统数据;使用系统诊断;使用System.Linq;使用Microsoft.Win32;命名空间SqlServerEnumerator{类程序{staticvoidMain(string[]args){Dictionary>>methods=newDictionary>>{{"CallSqlBrowser",GetLocalSqlServerInstancesByCallingSqlBrowser},{"CallSqlWmi32",GetLocalSqlServerInstancesByCallingSqlWmi32},{"CallSqlWmi64",GetLocalSqlServerInstancesByCallingSqlWmi64},{"ReadRegInstalledInstances",GetLocalSqlServerInstancesByReadingRegInstalledInstances},{"ReadRegInstanceNames",GetLocalSqlServerInstancesByReadingRegInstanceNames},{"CallSqlCmd",GetLocalSqlServerInstancesByCallingSqlCmd},};Dictionary>dictionary=methods.AsParallel().ToDictionary(v=>v.Key,v=>v.Value().OrderBy(n=>n,StringComparer.OrdinalIgnoreCase).ToList());foreach(KeyValuePair>pairindictionary){Console.WriteLine(string.Format("~~{0}~~",pair.Key));pair.Value.ForEach(v=>Console.WriteLine(""+v));}Console.WriteLine("按任意键继续。");控制台.ReadKey();}privatestaticListGetLocalSqlServerInstancesByCallingSqlBrowser(){DataTabledt=SmoApplication.EnumAvailableSqlServ错误(真);返回dt.Rows.Cast().Select(v=>v.Field("Name")).ToList();}privatestaticListGetLocalSqlServerInstancesByCallingSqlWmi32(){returnLocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use32bit);}privatestaticListGetLocalSqlServerInstancesByCallingSqlWmi64(){returnLocalSqlServerInstancesByCallingSqlWmi(ProviderArchitecture.Use64bit);}privatestaticListLocalSqlServerInstancesByCallingSqlWmi(ProviderArchitectureproviderArchitecture){try{ManagedComputermanagedComputer32=newManagedComputer();managedComputer32.ConnectionSettings.ProviderArchitecture=providerArchitecture;conststringdefaultSqlInstanceName="MSSQLSERVER";返回managedComputer32.ServerInstances.Cast().Select(v=>(string.IsNullOrEmpty(v.Name)||string.Equals(v.Name,defaultSqlInstanceName,StringComparison.OrdinalIgnoreCase))?v.Parent.Name:string.Format("{0}\{1}",v.Parent.Name,v.Name)).OrderBy(v=>v,StringComparer.OrdinalIgnoreCase).ToList();}catch(SmoExceptionex){Console.WriteLine(ex.Message);返回新列表();}catch(Exceptionex){Console.WriteLine(ex);返回新列表();}}privatestaticListGetLocalSqlServerInstancesByReadingRegInstalledInstances(){try{//HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoftSQLServerInstalledInstancesstring[]instances=null;使用(RegistryKeyrk=Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftMicrosoftSQLServer")){if(rk!=null){instances=(string[])rk.GetValue("InstalledInstances");}实例=实例??新字符串[]{};}返回GetLocalSqlServerInstances(实例);}catch(Exceptionex){Console.WriteLine(ex);返回新列表();}}privatestaticListGetLocalSqlServerInstancesByReadingRegInstanceNames(){try{//HKEY_LOCAL_MACHINESOFTWAREMicrosoftMicrosoftSQLServerInstanceNamesSQLstring[]instances=null;使用(RegistryKeyrk=Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftMicrosoftSQLServerInstanceNamesSQL")){if(rk!=null){instances=rk.GetValueNames();}instances=instances??newstring[]{};}returnGetLocalSqlServerInstances(instances);}catch(异常ex){Console.WriteLine(ex);returnnewList();}}privatestaticListGetLocalSqlServerInstances(string[]instanceNames){字符串machineName=Environment.MachineName;conststringdefaultSqlInstanceName="MSSQLSERVER";returninstanceNames.Select(v=>(string.IsNullOrEmpty(v)||string.Equals(v,defaultSqlInstanceName,StringComparison.OrdinalIgnoreCase))?machineName:string.Format("{0}\{1}",machineName,v)).ToList();}privatestaticListGetLocalSqlServerInstancesByCallingSqlCmd(){try{//SQLCMD-LintexitCode;字符串输出;CaptureConsoleAppOutput("SQLCMD.exe","-L",200,outexitCode,outoutput);if(exitCode==0){字符串machineName=Environment.MachineName;returnoutput.Split(new[]{"rn","r","n"},StringSplitOptions.RemoveEmptyEntries).Select(v=>v.Trim()).Where(v=>!string.IsNullOrEmpty(v)).Where(v=>string.Equals(v,"(local)",StringComparison.Ordinal)||v.StartsWith(machineName,StringComparison.OrdinalIgnoreCase)).Select(v=>string.Equals(v,"(local)",StringComparison.Ordinal)?machineName:v).Distinct(StringComparer.OrdinalIgnoreCase).列表();}返回新列表();}catch(Exceptionex){Console.WriteLine(ex);返回新列表();}}privatestaticvoidCaptureConsoleAppOutput(stringexeName,stringarguments,inttimeoutMilliseconds,outintexitCode,outstringoutput){using(Processprocess=newProcess()){process.StartInfo.FileName=exeName;process.StartInfo.Arguments=参数;process.StartInfo.UseShellExecute=false;process.StartInfo.RedirectStandardOutput=true;process.StartInfo.CreateNoWindow=true;过程。开始();output=process.StandardOutput.ReadToEnd();boolexited=process.WaitForExit(timeoutMilliseco发现);如果(退出){exitCode=process.ExitCode;}else{退出代码=-1;}}}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:

最新推荐
猜你喜欢