System.Runtime.InteropServices.COMException while trying to create a system restore point using C#

1.9k views Asked by At

I'm using the following C# code from this stackoverflow post.

ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default");
ManagementPath oPath = new ManagementPath("SystemRestore");
ObjectGetOptions oGetOp = new ObjectGetOptions();
ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);

ManagementBaseObject oInParams =
     oProcess.GetMethodParameters("CreateRestorePoint");
oInParams["Description"] = "Setting restore point";
oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS
oInParams["EventType"] = 100;

ManagementBaseObject oOutParams =
     oProcess.InvokeMethod("CreateRestorePoint", oInParams, null);

The error is coming from the line which declares oOutParams.

I've wrapped this line in a try catch, and printed out the error code which is -2147023838 which I cannot find in any list of COM error codes listed here (assuming the printed error code should be converted to hex 2's complement -> 0x80070422).

Without catching the exception (so basically the exact code above), the stack trace is:

Unhandled Exception: System.Runtime.InteropServices.COMException
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters, InvokeMethodOptions options)
   at WindowsUpdatesDev.Program.Main(String[] args)

With the try/catch wrapped around the line that declares oOutParams I print the stack trace which is:

at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters, InvokeMethodOptions options)                                                                                                           
at WindowsUpdatesDev.Program.Main(String[] args)

There is no message for this second stack trace.

2

There are 2 answers

1
Ed. On

Following steps here (specifically, all of step one and step two by setting 'Protection' to 'On' for my C: drive) allows the code above to run without errors.

0
Aron On

Just to follow up on my own experience here, and as Ed said in his answer:

Make sure that your system is configured to allow you to set a restore point.

You can do this by performing the following steps:

  1. Click the Windows key
  2. Type "Create a restore point" and open the application suggested
  3. Under the "System Protection" tab, make sure the protection is "On" for at least one of your drives