Getting drive info from a remote computer

user1865670 picture user1865670 · Jan 21, 2013 · Viewed 20.7k times · Source

I can view a remotly connected pc from this article:Remote Desktop using c-net . but i dont need it. I just have to connect with that pc and get the free space data of C drive. How could i do this? I can connect to a remote desktop. I can get driveInfo using IO namespace. but how to combine them?

Answer

Lance U. Matthews picture Lance U. Matthews · Jan 21, 2013

Use the System.Management namespace and Win32_Volume WMI class for this. You can query for an instance with a DriveLetter of C: and retrieve its FreeSpace property as follows:

ManagementPath path = new ManagementPath() {
    NamespacePath = @"root\cimv2",
    Server = "<REMOTE HOST OR IP>"
};
ManagementScope scope = new ManagementScope(path);
string condition = "DriveLetter = 'C:'";
string[] selectedProperties = new string[] { "FreeSpace" };
SelectQuery query = new SelectQuery("Win32_Volume", condition, selectedProperties);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
using (ManagementObjectCollection results = searcher.Get())
{
    ManagementObject volume = results.Cast<ManagementObject>().SingleOrDefault();

    if (volume != null)
    {
        ulong freeSpace = (ulong) volume.GetPropertyValue("FreeSpace");

        // Use freeSpace here...
    }
}

There is also a Capacity property that stores the total size of the volume.