簡體   English   中英

檢查是否已安裝SQL Server C#

[英]Check if SQL Server is installed C#

我正在用C#完成一個包含SQL Server數據庫的應用程序。

如何檢查用戶是否已安裝SQL Server 2012 Express本地數據庫?

是否可以通過注冊表在x86和x64上進行檢查?

基本上,這種想法是,如果用戶沒有安裝SQL Server,則應用程序建議安裝它。

作為安裝程序的安裝程序,我不依賴SQL Server 2012 Express本地數據庫。

謝謝。

您必須遍歷卸載GUID,並找到一個以關鍵字“ Microsoft SQL Server 2012”開頭的。 您可以通過以下方法找到它:轉到控制面板>程序和功能>並查看“顯示名稱”列。

// HKEY_LOCAL_MACHINE \\ SOFTWARE \\ Wow6432Node \\ Microsoft \\ Windows \\ CurrentVersion \\ Uninstall {guidVariable} \\ DisplayName

..應該與“ Microsoft SQL Server 2012 *”通配符匹配。

我沒有確切的代碼,但這應該可以幫助您入門。 只需遍歷“卸載”鍵的所有子項,然后通過獲取值來找到“ DisplayName”鍵。 下面的“ GUID”變量應該是您的迭代器,因為您不知道該值。 我確定您可以獲得作為“卸載”鍵的子鍵的所有GUID值的列表。

string UninstallRegKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
Guid UninstallGuid = new Guid(GUID);

using (RegistryKey key = Registry.LocalMachine.OpenSubKey(UninstallRegKeyPath, true))
{
    if (key == null)
    {
        return;
    }
    try
    {
        string guidText = UninstallGuid.ToString("B");
        RegistryKey child = key.OpenSubKey(guidText);
        if (child != null)
        {
        string displayName = child.GetValue("DisplayName").ToString();
        if (displayName.Contains("Microsoft SQL Server 2012"))
        {
            // implement logic when MSSQL 2012 is found
        }       
        child.Close();
        }
    }
}

小心點。 有32位安裝和64位安裝。 我相信Wow6432Node包含32位程序,因此默認情況下,所有C:\\Program Files (x86)\\都安裝在C:\\Program Files (x86)\\ (但可能在任何地方)。 對於所有64位程序,還有另一個位置可供我查找,該位置默認情況下安裝在C:\\Program Files\\ (並且可能再次安裝在任何地方)。

編輯:

嘗試這個。 您可能還想用“ CurrentUser”替換“ LocalMachine”,因為許多安裝程序允許您為您的用戶或所有用戶配置它們。

        using (RegistryKey root = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"))
        {
            string searchKey = @"Microsoft SQL Server 2012";
            string subKeyName = "DisplayName";

            foreach (string keyname in root.GetSubKeyNames())
            {
                //Console.WriteLine(keyname);
                using (RegistryKey key = root.OpenSubKey(keyname))
                {
                    try  // in case "DisplayName doesn't exist
                    {
                        string displayName = key.GetValue(subKeyName).ToString();
                        if (displayName.StartsWith(searchKey))
                            Console.WriteLine("GUID: " + keyname + Environment.NewLine + displayName + Environment.NewLine);
                    }
                    catch
                    {

                    }

                }
            }
        }

        Console.ReadLine();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM