Yeah, there's not much C# sample code for WMI anywhere -- including MSDN. That really sucks because WMI isn't very intuitive. I tested WMI for 8+ years and still struggle with some features... :wtf: The DefragAnalysis method returns 3 things: return code (which you got), a bool that indicates whether or not a defrag is recommended, and an instance of Win32_DefragAnalysis. The bool & instance get "wrapped" in an object array. All you have to do is tell the method where to put the objects. Think of the "outParams" array as a mailbox with 2 slots. Null values are fine. Here's some sample code. (Note, it isn't necessary to specify scope for Vista or Server 2008 because the defaults are local machine & “root\cimv2”. I only included it for backward compatibility.)
using System;
using System.Management;
namespace DefragAnalysis
{
class Program
{
static void Main(string[] args)
{
try
{
string scope = @"\\.\root\cimv2";
string query = @"SELECT * FROM Win32_Volume WHERE Name = 'C:\\'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
object[] outputArgs = new object[2];
foreach (ManagementObject volume in searcher.Get())
{
UInt32 result = (UInt32)volume.InvokeMethod("DefragAnalysis", outputArgs);
if (result == 0)
{
Console.WriteLine("Defrag Needed = {0}\\n", outputArgs\[0\]);
ManagementBaseObject defragAnalysis = outputArgs\[1\] as ManagementBaseObject;
if (null != defragAnalysis)
{
foreach (PropertyData property in defragAnalysis.Properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.Value);
}
}
}
else
{
Console.WriteLine("Method return code = 0x{0:X}", result);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Something bad happened.\\n" + ex);
}
finally
{
Console.WriteLine("\\npress any key to exit...");
Console.ReadKey();
}
}