Wednesday, September 19, 2012

Create System Restore Point

In today's post I want to show, how to create a system restore point using C#.
Therefor we use management classes, which connects with the Windows Management Instrumentation (WMI) and over this way reads information about the computer.
To run the project, via Project - Add Reference System.Management has to be included, furthermore this via using. The application also needs to run with administratrative rights.
Central point is an instance of the class ManagementClass.
Its constructor expects 3 parameters:
First a scope, which is here set to the local computer, then a path, which defines the operation to be executed (here: create a restore point) and lastly a class with options, for that we hand over the default options of a WMI call.
From the created instance the function GetMethodParameters() with the parameter "CreateRestorePoint" is called. This tells the application, to load the parameters of the WMI function "CreateRestorePo", so that these can be filled then. CreateRestorePoint expects 3 parameters:
  • Description: Description of the restore point
  • RestorePointType: Type of the restore point. Detailed information about the possible options can for example be found on this site. Here we hand over 0, which means, that an application was installed. A 10 would for example mean, that a driver was installed. 
  • EventType: Type of the event. We here hand over 100, which indicates, that a change has begun in the system. 101 would mean, that the change was done.
Finally we execute the action caling InvokeMethod and thus create a system restore point.
The code:

                // select local computer
                ManagementScope ManScope = new ManagementScope(@"\\localhost\root\default");
                // create system restore point
                ManagementPath ManPath = new ManagementPath("SystemRestore");
                // select default options
                ObjectGetOptions ManOptions = new ObjectGetOptions();
                // create management class with previous options
                ManagementClass ManClass = new ManagementClass(ManScope, ManPath, ManOptions);
                // load function parameters
                ManagementBaseObject ManBaseObject = ManClass.GetMethodParameters("CreateRestorePoint");
                // description
                ManBaseObject["Description"] = "Mein C# Wiederherstellungspunkt";
                // type of the restore point
                ManBaseObject["RestorePointType"] = 0;
                // ype of the event
                ManBaseObject["EventType"] = 100;

                ManagementBaseObject OutParam = ManClass.InvokeMethod("CreateRestorePoint", ManBaseObject, null);

No comments:

Post a Comment