C# Determine OS Version in .NET 6 - c#

What is the correct way to determine the correct OS version in .NET 6?
I found many different solutions regarding this topic. All of them are quite out of date I think.
I want to get something like "Windows 10 Enterprise build 22000 (64 bit)"
Environment.OSVersion.ToString()
gives "Microsoft Windows NT 10.0.22000.0"
RuntimeInformation.OSDescription
gives "Microsoft Windows 10.0.22000.0"
RuntimeInformation.OSArchitecture.ToString()
gives "X64"
So far I'm using:
Console.WriteLine(RuntimeInformation.OSDescription + " | " + RuntimeInformation.OSArchitecture.ToString())
This gives "Microsoft Windows 10.0.22000.0 | X64"
Is there a way to get something like "Windows 10 Enterprise | X64" in .NET 6?
In addition to that, I'm looking for a way to get the Windows install language and the current language.

The function:
RuntimeInformation.OSArchitecture.ToString();
returns the architecture that the OS was compiled, that is, in this case it was x86-64 (string-shaped)
The functions:
Environment.OSVersion.ToString()
RuntimeInformation.OSDescription
returns windows version
With this and with this link here:
(Get OS Version / Friendly Name in C#) we can get to this code:
using System.Runtime.InteropServices;
using System.Management;
static int GetARCHFriendlyBits(Architecture architecture)
{
return architecture switch
{
Architecture.X64 => 64,
Architecture.X86 => 32,
Architecture.Arm64 => 64,
Architecture.Arm => 32,
Architecture.Wasm => -1,
Architecture.S390x => -1,
_ => -1,
};
}
static string GetOSFriendlyName1()
{
string result = string.Empty;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
ManagementObjectSearcher searcher = new("SELECT Caption FROM Win32_OperatingSystem");
ManagementObject os = searcher.Get().Cast<ManagementObject>().First();
if (os["Caption"].ToString() is string osResult)
result = osResult;
}
else
{
return $"{RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})";
}
if (result == string.Empty)
return $"{RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})";
else
return $"{result} build {Environment.OSVersion.Version.Build} ({GetARCHFriendlyBits(RuntimeInformation.OSArchitecture)} bits)";
}
static string GetOSFriendlyName2()
{
string result = string.Empty;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
ManagementObjectSearcher searcher = new("SELECT Caption FROM Win32_OperatingSystem");
ManagementObject os = searcher.Get().Cast<ManagementObject>().First();
if (os["Caption"].ToString() is string osResult)
result = osResult;
}
else
{
return $"{RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})";
}
if (result == string.Empty)
return $"{RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})";
else
return $"{result} | {RuntimeInformation.OSArchitecture}";
}
Console.WriteLine(GetOSFriendlyName1());
Console.WriteLine(GetOSFriendlyName2());
which in my case writes this line here on the console:
Microsoft Windows 11 Home Single Language build 22621 (64 bits)
Microsoft Windows 11 Home Single Language | X64
To use System.Management, I had to install microsoft NuGet System.Management

Related

How to get Windows' Cumulative Update Version? [duplicate]

It seems that the word "version" in reference to Windows is used for different things. For example, the Windows 10 "Anniversary Update" is labeled "Version 1607" by Microsoft (here for example). But if I try to get the "Version" (on a PC with the Anniversary Update installed) using the following code, nothing is returned that looks like "1607".
// Get Version details
Version ver = os.Version;
Console.WriteLine("Major version: " + ver.Major);
Console.WriteLine("Major Revision: " + ver.MajorRevision);
Console.WriteLine("Minor version: " + ver.Minor);
Console.WriteLine("Minor Revision: " + ver.MinorRevision);
Console.WriteLine("Build: " + ver.Build);
I get this:
Major version: 6
Major Revision: 0
Minor version: 2
Minor Revision: 0
Build: 9200
How do I get the Windows 10 "version" as in "Version 1607"?
Thanks!
according to MSDN official link there's a specific version number for each windows version out there. in dot net this can be read using the Environment.OSVersion object.
Console.WriteLine("OSVersion: {0}", Environment.OSVersion);
//output: OSVersion: Microsoft Windows NT 6.2.9200.0
What you are looking for is called ReleaseID not a version of windows.
this be can read from registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ReleaseId
using Microsoft.Win32;
string releaseId = Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ReleaseId", "").ToString();
Console.WriteLine(releaseId);
string Version = (string)Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion", "ProductName", null);
Gives a name like "Windows 10 Enterprise".
private static ManagementObject GetMngObj(string className)
{
var wmi = new ManagementClass(className);
foreach (var o in wmi.GetInstances())
{
var mo = (ManagementObject)o;
if (mo != null) return mo;
}
return null;
}
public static string GetOsVer()
{
try
{
ManagementObject mo = GetMngObj("Win32_OperatingSystem");
if (null == mo)
return string.Empty;
return mo["Version"] as string;
}
catch (Exception e)
{
return string.Empty;
}
}
How to Use:
Console.WriteLine(GetOsVer());
Result: 10.0.0.1299
In addition to Scott's answer, you can also get the product name (ex. Windows 10 Pro) with this (*I take no credit as Scott is the one who mentioned the registry path + I'm reusing his code below):
using Microsoft.Win32;
string ProductName =
Registry.GetValue(#"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", "").ToString();
Console.WriteLine(ProductName);

Get current version OS in Windows 10 in C#

I Use C#. I try to get the current version of the OS:
OperatingSystem os = Environment.OSVersion;
Version ver = os.Version;
I get on the Windows 10: 6.2.
But 6.2 is Windows 8 or WindowsServer 2012 (Detect Windows version in .net)
I found the following solution (How can I detect if my app is running on Windows 10).
static bool IsWindows10()
{
var reg = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
string productName = (string)reg.GetValue("ProductName");
return productName.StartsWith("Windows 10");
}
This is the best way to get the current version in C#?
Add application manifest to your application and add the supportedOS Id of Windows 8.1 and Windows 10 to the manifest:
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
<!-- Windows 8.1 -->
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
</application>
</compatibility>
Now Environment.OSVersion includes the correct data for Windows 8.1 and Windows 10 and not 6.2 to indicate you run Windows 8. This is a change since Windows 8.1.
Here is a link from Microsoft offical, indicating how to get the System Version. It actually is a call to the Version API Helper Functions
So basically you must convert this code into C# because it's in C++, then keep only the Windows 10 part...
#include <windows.h>
#include <stdio.h>
#include <VersionHelpers.h>
int
__cdecl
wmain(
__in int argc,
__in_ecount(argc) PCWSTR argv[]
)
{
UNREFERENCED_PARAMETER(argc);
UNREFERENCED_PARAMETER(argv);
if (IsWindows10OrGreater())
{
printf("Windows10OrGreater\n");
}
}
And if you like trying to read code, you can check out this one link. This DLL can be used to get information on the OS...
I have created this simple method in C# and it has worked for me.
public static string GetWindowsVersion()
{
string registryPath = "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion";
string build = null;
int number = 0;
try
{
build = Registry.GetValue(registryPath, "CurrentBuild", null).ToString();
}
catch { return null; }
number = Int32.Parse(build);
if (number == 7601)
return "Windows 7";
else if (number == 9200)
return "Windows 8";
else if (number == 9600)
return "Windows 8.1";
else if (number >= 10240 && number <= 19045)
return "Windows 10";
else if (number >= 22000)
return "Windows 11";
else
return "Older version";
/* Go here to find more build numbers and evaluate more conditions
*
* https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions
*
*/
}

Can I tell the difference between windows desktop and server in C# [duplicate]

I am looking for an elegant way to get the OS version like: "Windows XP Professional Service Pack 1" or "Windows Server 2008 Standard Edition" etc.
Is there an elegant way of doing that?
I am also interested in the processor architecture (like x86 or x64).
You can use WMI to get the product name ("Microsoft® Windows Server® 2008 Enterprise "):
using System.Management;
var name = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault();
return name != null ? name.ToString() : "Unknown";
You should really try to avoid WMI for local use. It is very convenient but you pay dearly for it in terms of performance. This is quick and simple:
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 "";
}
Why not use Environment.OSVersion? It will also tell you what operating this is - Windows, Mac OS X, Unix, etc. To find out if you are running in 64bit or 32bit, use IntPtr.Size - this will return 4 bytes for 32bit and 8 bytes for 64bit.
Try:
new ComputerInfo().OSVersion;
Output:
Microsoft Windows 10 Enterprise
Note:
Add reference to Microsoft.VisualBasic.Devices;
For me below line works which gives me output like:
Microsoft Windows 10.0.18362
System.Runtime.InteropServices.RuntimeInformation.OSDescription
It can be used to get information like architecture as well
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation?view=netframework-4.8
Properties
FrameworkDescription: Returns a string that indicates the name of the .NET installation on which an app is running.
OSArchitecture: Gets the platform architecture on which the current app is running.
OSDescription: Gets a string that describes the operating system on which the app is running.
ProcessArchitecture: Gets the process architecture of the currently running app.
Little late, but this is how I did it. Might help someone in the future.
using Microsoft.Win32;
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion");
string pathName = (string)registryKey.GetValue("productName");
Sample output:
Name = Windows Vista
Edition = Home Premium
Service Pack = Service Pack 1
Version = 6.0.6001.65536
Bits = 64
Sample class:
class Program
{
static void Main( string[] args )
{
Console.WriteLine( "Operation System Information" );
Console.WriteLine( "----------------------------" );
Console.WriteLine( "Name = {0}", OSInfo.Name );
Console.WriteLine( "Edition = {0}", OSInfo.Edition );
Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
Console.WriteLine( "Version = {0}", OSInfo.VersionString );
Console.WriteLine( "Bits = {0}", OSInfo.Bits );
Console.ReadLine();
}
}
Source code for OSInfo class: http://www.csharp411.com/determine-windows-version-and-edition-with-c/ However there is an error in the code, you will need to replace the "case 6" statement (it's just before #endregion NAME) with this:
case 6:
switch (minorVersion)
{
case 0:
switch (productType)
{
case 1:
name = "Windows Vista";
break;
case 3:
name = "Windows Server 2008";
break;
}
break;
case 1:
switch (productType)
{
case 1:
name = "Windows 7";
break;
case 3:
name = "Windows Server 2008 R2";
break;
}
break;
}
break;
And if you want to go a step further and see if your program is running in 64 or 32 bit:
public static class Wow
{
public static bool Is64BitProcess
{
get { return IntPtr.Size == 8; }
}
public static bool Is64BitOperatingSystem
{
get
{
// Clearly if this is a 64-bit process we must be on a 64-bit OS.
if (Is64BitProcess)
return true;
// Ok, so we are a 32-bit process, but is the OS 64-bit?
// If we are running under Wow64 than the OS is 64-bit.
bool isWow64;
return ModuleContainsFunction("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out isWow64) && isWow64;
}
}
static bool ModuleContainsFunction(string moduleName, string methodName)
{
IntPtr hModule = GetModuleHandle(moduleName);
if (hModule != IntPtr.Zero)
return GetProcAddress(hModule, methodName) != IntPtr.Zero;
return false;
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
extern static bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool isWow64);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
extern static IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
extern static IntPtr GetProcAddress(IntPtr hModule, string methodName);
}
One thing to be careful of is this information is usually localized and will report differently depending on the language of the OS.
You can get a lot of info from WMI look for the Win32_OperatingSystem class
Note that the processor architecture question is complex:
do you mean (higher numers require lower numbers to be true):
The CPU is capable for handling 64bit (in the sense that it supports AMD/intel x64 or Itanium)
The Operating system is 64bit
GPR and pointers are 64bits, i.e. XP 64, Vista 64, a 64 bit server release or a 64bit OS for mono
The currently executing process is a 64 bit process (not executing under Wow64 for example)
if you are happy that all 3 must be true then
IntPtr.Size == 8
Indicates that all three are true
You can use Visual Basic Devices to get version information.
Code:
using Microsoft.VisualBasic.Devices;
var versionID = new ComputerInfo().OSVersion;//6.1.7601.65536
var versionName = new ComputerInfo().OSFullName;//Microsoft Windows 7 Ultimate
var verionPlatform = new ComputerInfo().OSPlatform;//WinNT
Console.WriteLine(versionID);
Console.WriteLine(versionName);
Console.WriteLine(verionPlatform);
Output:
6.1.7601.65536
Microsoft Windows 10 Enterprise
WinNT
Note:
You will need to add a reference to Microsoft.VisualBasic;
I know it is no direct answer to the question and it's also a little bit late, but for those who are only looking for a way to determine whether the OS is a Client OS or a server there is a way to use the following: (you need to include the System.Management reference)
using System;
using System.Management;
ManagementClass osClass = new ManagementClass("Win32_OperatingSystem");
foreach (ManagementObject queryObj in osClass.GetInstances())
{
foreach (PropertyData prop in queryObj.Properties)
{
if (prop.Name == "ProductType")
{
ProdType = int.Parse(prop.Value.ToString());
}
}
}
while the variable ProdType is an integer that was initialized before. It will contain a value between 1 and 3 while 1 stands for Workstation, 2 for Domain Controller and 3 for a server.
This was taken from Accessing the properties of Win32_OperatingSystem and changed a little bit...
Disclosure: After posting this, I realized that I am depending on a Nuget extension method library called Z.ExntensionMethods which contains IndexOf()
using Microsoft.VisualBasic.Devices;
string SimpleOSName()
{
var name = new ComputerInfo().OSFullName;
var parts = name.Split(' ').ToArray();
var take = name.Contains("Server")?3:2;
return string.Join(" ", parts.Skip(parts.IndexOf("Windows")).Take(take));
}
Faster performance using System.Management;
string SimpleOSName()
{
var name = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem")
.Get().Cast<ManagementObject>()
.Select(x => x.GetPropertyValue("Caption").ToString())
.First();
var parts = name.Split(' ').ToArray();
var take = name.Contains("Server")?3:2;
return string.Join(" ", parts.Skip(parts.IndexOf("Windows")).Take(take));
}
output example:
Windows 7
Windows Server 2008

Windows version in c# [duplicate]

This question already has answers here:
Detect Windows version in .NET
(18 answers)
Closed 6 years ago.
I want to know which Windows version the PC has.. in C# Framework 3.5
I have tried using
OperatingSystem os = Environment.OSVersion;
Version ver = os.Version;
But the result is
Plataform: WIN32NT
version 6.2.9200
Version minor: 2
Version Major: 6
The problem is that I have "Windows 8 Pro"...
How can I detect it?
Thanks
You will have to match version numbers with the appropriate string value yourself.
Here is a list of the most recent Windows OS and their corresponding version number:
Windows Server 2016 & 2019 - 10.0*
Windows 10 - 10.0*
Windows 8.1 - 6.3*
Windows Server 2012 R2 - 6.3*
Windows 8 - 6.2
Windows Server 2012 - 6.2
Windows 7 - 6.1
Windows Server 2008 R2 - 6.1
Windows Server 2008 - 6.0
Windows Vista - 6.0
Windows Server 2003 R2 - 5.2
Windows Server 2003 - 5.2
Windows XP 64-Bit Edition - 5.2
Windows XP - 5.1
Windows 2000 - 5.0
*For applications that have been manifested for Windows 8.1 or 10. Applications not manifested for 8.1 / 10 will return the Windows 8 OS version value (6.2).
Here's the source.
Also, from the same source:
Identifying the current operating system is usually not the best way
to determine whether a particular operating system feature is present.
This is because the operating system may have had new features added
in a redistributable DLL. Rather than using the Version API Helper
functions to determine the operating system platform or version
number, test for the presence of the feature itself.
In my scenario I needed my application to capture computer info for possible bug-reports and statistics.
I did not find the solutions where an application manifest had to be added satisfactory. Most of the suggestions I found while googling this suggested just that, unfortunately.
Thing is, when using a manifest, each OS version has to be added manually to it in order for that particular OS version to be able to report itself at runtime.
In other words, this becomes a race condition: A user of my app may very well be using a version of my app that pre-dates the OS in use. I would have to upgrade the app immediately when a new OS version was launched by Microsoft. I would also have to force the users to upgrade the app at the same time as they updated the OS.
In other words, not very feasible.
After browsing through the options I found some references (surprisingly few compared to the app manifest) that instead suggested using registry lookups.
My (chopped down) ComputerInfo class with only WinMajorVersion, WinMinorVersion and IsServer properties looks like this:
using Microsoft.Win32;
namespace Inspection
{
/// <summary>
/// Static class that adds convenient methods for getting information on the running computers basic hardware and os setup.
/// </summary>
public static class ComputerInfo
{
/// <summary>
/// Returns the Windows major version number for this computer.
/// </summary>
public static uint WinMajorVersion
{
get
{
dynamic major;
// The 'CurrentMajorVersionNumber' string value in the CurrentVersion key is new for Windows 10,
// and will most likely (hopefully) be there for some time before MS decides to change this - again...
if (TryGeRegistryKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentMajorVersionNumber", out major))
{
return (uint) major;
}
// When the 'CurrentMajorVersionNumber' value is not present we fallback to reading the previous key used for this: 'CurrentVersion'
dynamic version;
if (!TryGeRegistryKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentVersion", out version))
return 0;
var versionParts = ((string) version).Split('.');
if (versionParts.Length != 2) return 0;
uint majorAsUInt;
return uint.TryParse(versionParts[0], out majorAsUInt) ? majorAsUInt : 0;
}
}
/// <summary>
/// Returns the Windows minor version number for this computer.
/// </summary>
public static uint WinMinorVersion
{
get
{
dynamic minor;
// The 'CurrentMinorVersionNumber' string value in the CurrentVersion key is new for Windows 10,
// and will most likely (hopefully) be there for some time before MS decides to change this - again...
if (TryGeRegistryKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentMinorVersionNumber",
out minor))
{
return (uint) minor;
}
// When the 'CurrentMinorVersionNumber' value is not present we fallback to reading the previous key used for this: 'CurrentVersion'
dynamic version;
if (!TryGeRegistryKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentVersion", out version))
return 0;
var versionParts = ((string) version).Split('.');
if (versionParts.Length != 2) return 0;
uint minorAsUInt;
return uint.TryParse(versionParts[1], out minorAsUInt) ? minorAsUInt : 0;
}
}
/// <summary>
/// Returns whether or not the current computer is a server or not.
/// </summary>
public static uint IsServer
{
get
{
dynamic installationType;
if (TryGeRegistryKey(#"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "InstallationType",
out installationType))
{
return (uint) (installationType.Equals("Client") ? 0 : 1);
}
return 0;
}
}
private static bool TryGeRegistryKey(string path, string key, out dynamic value)
{
value = null;
try
{
var rk = Registry.LocalMachine.OpenSubKey(path);
if (rk == null) return false;
value = rk.GetValue(key);
return value != null;
}
catch
{
return false;
}
}
}
}
I released the OsInfo nuget to easily compare Windows versions.
bool win8OrLess = Environment.OSVersion.IsLessThanOrEqualTo(OsVersion.Win8);
bool winXp = Environment.OSVersion.IsEqualTo(OsVersion.WinXP);
int? servicePack = Environment.OSVersion.GetServicePackVersion();
bool is64bit = Environment.OSVersion.Is64Bit(); // Already covered in .NET 4.5+
Try this:
using System.Management;
private string fnGetFriendlyName()
{
var name = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
select x.GetPropertyValue("Caption")).FirstOrDefault();
return name != null ? name.ToString() : "Unknown";
}
Source: https://stackoverflow.com/a/2016557/3273962

availability of Win32_MountPoint and Win32_Volume on Windows XP?

From the MSDN articles I've found -- http://msdn.microsoft.com/en-us/library/aa394515(v=VS.85).aspx -- Win32_Volume and Win32_MountPoint aren't available on Windows XP.
However, I'm developing a C# app on Windows XP (64bit), and I can get to those WMI classes just fine. Users of my app will be on Windows XP sp2 with .Net 3.5 sp1.
Googling around, I can't determine whether I can count on this or not.
Am I successful on my system because of one or more of the following:
- windows xp service pack 2?
- visual studio 2008 sp1 was installed?
- .Net 3.5 sp1?
Should I use something other than WMI to get at the volume/mountpoint info?
Below is sample code that's working...
public static Dictionary<string, NameValueCollection> GetAllVolumeDeviceIDs()
{
Dictionary<string, NameValueCollection> ret = new Dictionary<string, NameValueCollection>();
// retrieve information from Win32_Volume
try
{
using (ManagementClass volClass = new ManagementClass("Win32_Volume"))
{
using (ManagementObjectCollection mocVols = volClass.GetInstances())
{
// iterate over every volume
foreach (ManagementObject moVol in mocVols)
{
// get the volume's device ID (will be key into our dictionary)
string devId = moVol.GetPropertyValue("DeviceID").ToString();
ret.Add(devId, new NameValueCollection());
//Console.WriteLine("Vol: {0}", devId);
// for each non-null property on the Volume, add it to our NameValueCollection
foreach (PropertyData p in moVol.Properties)
{
if (p.Value == null)
continue;
ret[devId].Add(p.Name, p.Value.ToString());
//Console.WriteLine("\t{0}: {1}", p.Name, p.Value);
}
// find the mountpoints of this volume
using (ManagementObjectCollection mocMPs = moVol.GetRelationships("Win32_MountPoint"))
{
foreach (ManagementObject moMP in mocMPs)
{
// only care about adding directory
// Directory prop will be something like "Win32_Directory.Name=\"C:\\\\\""
string dir = moMP["Directory"].ToString();
// find opening/closing quotes in order to get the substring we want
int first = dir.IndexOf('"') + 1;
int last = dir.LastIndexOf('"');
string dirSubstr = dir.Substring(first , last - first);
// use GetFullPath to normalize/unescape any extra backslashes
string fullpath = Path.GetFullPath(dirSubstr);
ret[devId].Add(MOUNTPOINT_DIRS_KEY, fullpath);
}
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Problem retrieving Volume information from WMI. {0} - \n{1}",ex.Message,ex.StackTrace);
return ret;
}
return ret;
}
I guess the Win32_MountPoint and Win32_Volume classes are available on Windows XP Professional x64 Edition because it's based on the Windows Server 2003 codebase. On 32-bit versions of Windows XP, these classes don't exist and to perform your task you need to P/Invoke native volume management functions, like Tim said.
You may need to pinvoke into the Win32 Volume Management Functions

Categories