How to obtain DefragAnalysis using C#


I am currently developing an application in C# (.NET 4.0) that should have as a part of its functionality the ability to determine the percentage of fragmentation on a particular volume. All the other features have been tested and are working fine but I’ve hit a snag trying to access this data. I would ideally prefer to use WMI as this matches the format I’m using for the other features but at this point I’m willing to use anything that can be efficiently integrated into the application, even if I have to use RegEx to filter the data. I am currently doing the development on a Windows 7 Professional (x64) machine. I have tested the following Powershell snippet using Administrator rights and it works flawlessly.

This is the method I’m using in C# to accomplish the same thing, but the InvokeMethod keeps returning 11 (0xB).

I have even added the following line to the app.manifest but still nothing.

Could somebody please tell me what I’m overlooking? Failure is not an option for me on this, so if it cannot be done using C# I don’t mind creating a DLL in another language (even if I have to learn it), that will give me the results I need. Ideally the application should be able work on any OS from XP upwards and must be totally transparent to the user.

These are the resources I have already used. I wanted to add the jeffrey_wall blog on msdn as well but as a new user I can only add 2 hyperlinks at a time. Thanks again.


Try building your application targeting ‘Any CPU’ – on the Build tab of the project properties. I suspect you’re using a target of x86. I get the same error code on my Win7 x64 machine if I do that.

In fact, running your PowerShell snippet in the x86 version of PowerShell gives an empty set of results, too.

You get the same error if you run either piece of code without full Administrator privileges, as you’ve found, so also ensure your app.manifest is correct. A UAC prompt is a handy hint that it’s taking effect!

No idea why this WMI query doesn’t like running under WoW64, I’m afraid, but hopefully this will give you a head-start.


How to obtain DefragAnalysis using C# by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply