Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get OS Version / Friendly Name in C#

I am currently working on a C# project. I want to collect users statistics to better develop the software. I am using the Environment.OS feature of C# but its only showing the OS name as something like Microsoft Windows NT

What I want to be able to retrieve is the actual known name of the OS like whether it is Windows XP, Windows Vista or Windows 7 and etc.

Is this possible?

like image 239
Boardy Avatar asked Jun 13 '11 14:06

Boardy


People also ask

How do I get OS version from WMIC?

You can use wmic os get commands on a Microsoft Windows system to view information related to the operating system via a command-line interface (CLI). E.g., to determine the version of the operating system you can issue the command Windows Management Instrumentation Command-line (WMIC) command wmic os get version .


2 Answers

Add a reference and using statements for System.Management, then:

public static string GetOSFriendlyName() {     string result = string.Empty;     ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem");     foreach (ManagementObject os in searcher.Get())     {         result = os["Caption"].ToString();         break;     }     return result; } 
like image 190
George Duckett Avatar answered Sep 23 '22 06:09

George Duckett


You should really try to avoid WMI for local use. It is very convenient but you pay dearly for it in terms of performance. Think laziness tax!

Kashish's answer about the registry does not work on all systems. Code below should and also includes the service pack:

    public string HKLM_GetString(string path, string key)     {         try         {             RegistryKey rk = Registry.LocalMachine.OpenSubKey(path);             if (rk == null) return "";             return (string)rk.GetValue(key);         }         catch { return ""; }     }      public string FriendlyName()     {         string ProductName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");         string CSDVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");         if (ProductName != "")         {             return (ProductName.StartsWith("Microsoft") ? "" : "Microsoft ") + ProductName +                         (CSDVersion != "" ? " " + CSDVersion : "");         }         return "";     } 
like image 24
domskey Avatar answered Sep 21 '22 06:09

domskey