Use C # To compile a USB storage device trace detection and deletion Tool

Source: Internet
Author: User

Zookeeper

Write a USB storage device trace detection and deletion Tool

(C # Windows Form programming exercises)

[Copyright Qiu 2014 metaphysis@yeah.net, reprinted please indicate the source]

Section 1 Preparation

Previously, Visual Basic. Net was used to write Windows Form programs. These days, I have been familiar with the C # syntax and want to practice it. Some USB storage devices used trace detection and deletion tools before, so I wanted to write a small tool to simulate these features.

After the USB storage device is in use, some records will be left in the registry. Generally, the corresponding registry key value is retrieved to check the usage trace. These key values include:

HKEY_LOCAL_MACHINE \ SYSTEM \ ControlSetXXX (CurrentControSetXXX) \ Enum \ USB

HKEY_LOCAL_MACHINE \ SYSTEM \ ControlSetXXX (CurrentControSetXXX) \ Enum \ USBSTOR

HKEY_LOCAL_MACHINE \ SYSTEM \ ControlSetXXX (CurrentControSetXXX) \ Control \ DeviceClasses \ {53f56307-b6bf-11d0-94f2-00a0c91efb8b}

HKEY_LOCAL_MACHINE \ SYSTEM \ ControlSetXXX (CurrentControSetXXX) \ Control \ DeviceClasses \ {a5dcbf10-6530-11d2-901f-00c04fb951ed}

ControlSetXXX and CurrentControlSetXXX indicate subkeys similar to ControlSet001, ControlSet002, and CurrentControlSet in the registry. Generally, there is only one CurrentControlSet subkey. In special cases, there may be multiple subkeys, such as CurrentControlSet001, the same ControlSet generally only has ControlSet001 and ControlSet002. In special cases, there may be multiple). CurrentControlSet stores the current configuration information of the system, controlSet001 and so on are backups of the current configuration information. Generally, the Registry has more than two backups, and sometimes more backups. The information in ControlSetXXX is the same as that in CurrentControlSet. Therefore, when detecting and deleting the information of a USB storage device, you must check both the CurrentControlSet subkey and the ControlSetXXX subkey.

For Enum \ USB sub-keys, some information about the USB devices that have been connected to the system is stored, including USB mouse, keyboard, optical drive, mobile phone, mobile hard drive, camera, USB flash drive, etc, therefore, not all information is USB storage device information, although deleting this information is not serious (because only some connection information of these devices and the corresponding driver information are deleted, the system does not delete the actual driver files of the system, so the system will automatically re-identify these devices), but to improve the recognition accuracy, it is better to add some judgments.

For The Enum \ USBSTOR sub-keys, the information of the USB storage device is separated separately, the information stored under this sub-key is related to the USB storage device that has been connected to the computer. This information details the type, hardware ID, device description, and friendly name of the USB storage device.

For Control \ DeviceClasses, the sub-key stores device information classified by GUID, several of them are related to USB devices (they are the USBIODEF header file for Input and Output Control on Microsoft USB and storage devices. H and NTDDSTOR. H ):

{A5DCBF10-6530-11D2-901F-00C04FB951ED} GUID_DEVINTERFACE_USB_DEVICE

{3ABF6F2D-71C4-462A-8A92-1E6861E6AF27} GUID_DEVINTERFACE_USB_HOST_CONTROLLER

{F18A0E88-C30C-11D0-8815-00A0C906BED8} GUID_DEVINTERFACE_USB_HUB

{53F56307-B6BF-11D0-94F2-00A0C91EFB8B} GUID_DEVINTERFACE_DISK

General check {53F56307-B6BF-11D0-94F2-00A0C91EFB8B} and {A5DCBF10-6530-11D2-901F-00C04

FB951ED} these two key values, the other two because it is related to the USB controller, generally do not check. Some documents said that the MountedDevices sub-key should be checked. However, because the sub-key is related to the partition information of the system, it is generally not absolutely certain and does not need to be checked or deleted, this may cause unnecessary troubles.

Section 2 check the usage traces of USB storage devices

1. Open Visual Studio 2010 and create a blank solution named USB view.

2. In the solution, create a project of the "Windows Forms Application" type and name it USBViewer. Name the main form MainForm. Add some icons and PNG image resources to beautify the program interface.

The resource file contains a license file named vendorids.txt, which stores the ID number of the USB device manufacturer and the manufacturer name value pair, display the name of the manufacturer of the USB device found in the registry (the file content comes from the header file vndrc list in the Microsoft USB view sample program. h, the sample program is C ++ encoded and needs to be opened using Visual Studio 2013, and requires installation of Windows Driver Kit (WDK) 8.1, download link address http://code.msdn.microsoft.com/windowshardware/USBView-sample-application-e3241039 ).

After the necessary buttons are created, write the detection code. To read the registry, it is necessary to use the RegistryKey class provided by the. Net Framework. This requires reference to the Microsoft. Win32 namespace where the registry classes are located.

UsingMicrosoft. Win32;

Then we get the base item HKEY_LOCAL_MACHINE of the registry we are interested in, and then use the OpenSubKey method of the RegistryKey class to open the SYSTEM subkey in read-only mode.

RegistryKey hklm = Registry. LocalMachine;

RegistryKey systemKey = hklm. OpenSubKey ("SYSTEM ");

The. Net Framework has encapsulated the data in the Registry into a Registry class (note that the Registry class and RegistryKey class are different) and published several read-only attributes, which are:

The RegistryKey class is used to retrieve data in the registry. The following are the attributes and methods of the RegistryKey class used in this article:

SubKeyCount retrieves the number of subitems of the current item.

OpenSubKey (string) is read-only to retrieve the Sub-item identified by string.

OpenSubKey (string, bool) is used to retrieve the Sub-item identified by string in the way specified by bool. If the bool value is true, it indicates that the sub-item can be opened in read/write mode; otherwise, it is read-only.

DeleteSubKeyTree (string) recursively deletes the subitem of the string identifier and any subitem.

GetValue (string) retrieves the value associated with the name of a string. if the name of the string does not exist, null is returned.

GetSubKeyNames () returns an array of strings containing all subitem names.

Close () to Close the key. If there is any change, the change will be refreshed to the disk.

Note that if you want to open a subitem in writable mode for deletion or write operations, you must have the corresponding permissions; otherwise, a SecurityException exception is thrown. In the detection phase, the OpenSubKey (string) method can be used because only the read-only permission is required ). After the Local_Machine \ SYSTEM Sub-key is enabled, start to retrieve keys similar to ControlSetXXX and CurrentControlSetXXX under this key.

If (! SysKey. ToUpper (). StartsWith ("CONTROLSET ")&&

! SysKey. ToUpper (). StartsWith ("CURRENTCONTROLSET "))

Continue;

After finding such a sub-key, search for the sub-keys such as Enum \ USB, Enum \ usb stor, and Control \ DeviceClasses.

Because the information in the Enum \ USB sub-Keys is not all the information of the USB storage device, it is necessary to determine. Observe the items under Enum \ USB sub-keys:

Except ROOT_HUB20, other key values start with VID _, followed by a 4-bit hexadecimal number, which is the vendor's ID number, the following PID_XXXX is the manufacturer's product number. Open the subkey values of these vid_headers to view more information:

For example, the Service indicates that the USB device is processed by the system Service HidUSB, and the system Service HidUSB indicates the ergonomic input device using the USB protocol, if a USB-type mouse, keyboard, camera, or other device is connected to a computer, a HID device-specific event is triggered. The HidUSB service handles the event, you can see that the key value ClassGUID exists. The value {745a17a0-74d3-11d0-b6fe-00a0c90f57da} indicates that the Class is a device such as HIDClass. Similarly, USB storage devices are also processed by a service during access. This service is a USB stor system service. The following lists the names of services related to USB devices under Enum \ USB (there are other related services, which are listed on my system ):

USB ccgp: USB device controller service.

HidUsb: USB ergonomic engineering input device service.

USB stor: USB storage device service.

USB hub: USB device interface service.

WUDFRd: a service related to the Framework reflector driven by the user mode. This service is processed when only devices such as mobile phones are connected.

VboxUsb: this service appears after the VMVirtualBox Virtual Machine Software of Oracle is installed. It is used to process USB devices connected to the virtual machine.

In this article, only USB devices processed by the usb stor, WUDFRd, and VboxUsb services are detected. For Enum \ USBSTOR sub-keys, the structure is similar to that of Enum \ USB. The sub-key value of USB or USB stor contains the FriendlyName, which indicates the friendly name of the device and can be displayed as the name of the USB device.

Section 3 Delete the use marks of USB storage devices

After detection, these traces are deleted. Because some key-value permissions of the Registry are SYSTEM accounts, the General Administrator Account permissions cannot be deleted. to delete them using code, you must obtain the SYSTEM permission, one way is to make the deleted code into a program and install it as a SYSTEM service (Sysinterals tool javasxec also utilizes the feature that SYSTEM services can use SYSTEM permissions, so that the started process inherits the SYSTEM permission), the SYSTEM service can run on the SYSTEM permission, so that it has full control over the registry, you can delete and modify the Registry as needed (however, be sure not to delete other registry keys to avoid trouble ). How to Use Visual Studio to create system services, Step by Step.

1. Right-click solution USB view, select "add"-"New Project", select "Windows Service" for the project type, and name the project USBCleaner, the following method will appear in the code automatically generated by IDE:

Protectedoverridevoid OnStart (string [] args)

Protectedoverrisponid OnStop ()

Indicates the event processing process when the service is started and stopped. The code for deleting the registry key value is written during the processing of these two events. The logic is the same as that during detection. During the deletion process, I added a log function to record the success and error information during the deletion process. In order to generate a log file under the program running directory, You need to obtain the path of the system service during its operation. You have read some documents online and there are many ways to obtain the path, I did an experiment by registering the service. The results are as follows:

Assembly. GetExecutingAssembly (). Location

D: \ DATA \ USBViewer \ bin \ Release \ USBCleaner.exe

This. GetType (). Assembly. Location

D: \ DATA \ USBViewer \ bin \ Release \ USBCleaner.exe

Process. GetCurrentProcess (). MainModule. FileName

D: \ DATA \ USBViewer \ bin \ Release \ USBCleaner.exe

System. Environment. CurrentDirectory

C: \ Windows \ system32

System. AppDomain. CurrentDomain. BaseDirectory

D: \ DATA \ USBViewer \ bin \ Release \

System. AppDomain. CurrentDomain. SetupInformation. ApplicationBase

D: \ DATA \ USBViewer \ bin \ Release \

System. IO. Directory. GetCurrentDirectory ()

C: \ Windows \ system32

Finally, we decided to use the Assembly. GetExecutingAssembly (). Location method to get the correct results when running on Windows 7, Windows XP, and Windows Server 2003.

After all the deletion code is compiled, add the installer to the service. Double-click to open USB cleaner. cs, the design interface is displayed. Right-click the design interface and select "add installer" to add support for the Service Project during service installation, in this way, you can directly install and uninstall the service through code.

The "add installer" step will automatically add two components to the project. One is the service process installation Class component, and the other is the service installation Class component:

The service process installation component has the following attributes:

The "Account" attribute is the permission level for running the service. Select "LocalSystem" to use the SYSTEM permission. The other is a service installation component with the following attributes:

Key attributes:

Description is a brief Description of the service.

DisplayName: The name displayed in the service list.

The name of the ServiceName service. The system uses this name to uniquely identify the service and cannot conflict with an existing service.

StartType indicates the Service Startup method, which can be automatic, manual, or disabled.

After the configuration is complete, generate a USB cleaner and get an EXE file:

The connector is installed and called on usbcleaner.exe in the usbviewerproject.

For manual installation, you can use the. Net Framework tool InstallUtil.exe. For. NetFramework 4.0, it is generally located:

% SystemRoot % \ Microsoft. NET \ Framework \ v4.0.30319 \ InstallUtil.exe

Use/u or/uninstall to uninstall the service, and install the service without parameters. However, to automatically install and uninstall the service in the program, you need to use the transactedinstallerclass of the .netframework to compile the functions provided by the Installation tool of the installutil.exe service.

For better code organization, I put the code for running and installing the detection service in the ServiceHelper. cs file of the USBViewer project. The code first adds references to the following two namespaces:

UsingSystem. Configuration. Install;

UsingSystem. ServiceProcess;

The purpose of referencing System. Configuration. Install is to use the TransactedInstaller class, which is to Install or uninstall the service in a transaction mode, either Install or uninstall successfully, or return to the status before installation. Before performing the operation, perform a regular check on the service to check whether the service already exists. Here, the ServiceController class is used to round-robin The service name, as long as the service with the specified name is found, you can see that the service already exists.

///

/// Check whether the service is installed.

///

/// The name of the service to be queried.

///

Privatestatic boolIsWindowsServiceInstalled (string serviceName)

{

Service Controller [] services = ServiceController. GetServices ();

Foreach (ServiceController service in services)

{

If (service. ServiceName = serviceName)

Returntrue;

}

Returnfalse;

}

To install the service, call the TransactedInstaller class as follows:

String [] using line = {};

TransactedInstaller transactedInstaller = newTransactedInstaller ();

AssemblyInstaller assemblyInstaller = newAssemblyInstaller (serviceFileName, cmdline );

TransactedInstaller. Installers. Add (assemblyInstaller );

TransactedInstaller. Install (newSystem. Collections. Hashtable ());

Note that the Install method requires a variable of the IDictionary interface type to save the installation status. A hash table is used here. The Uninstall method is called when you Uninstall the service and install the service. You do not need to provide the Save status variable.

TransactedInstaller. Uninstall (null );

Before installing and uninstalling, do not forget to check the service file to be installed and uninstalled to ensure that the file exists.

// Check whether the corresponding service file exists.

String serviceFileName = Path. Combine (Application. StartupPath, "USBCleaner.exe ");

If (File. Exists (serviceFileName) = false)

Returnfalse;

Section 4 run the test

Compile the project USBViewer to obtain an EXE file:

The system service must be installed during the deletion process and the system administrator privilege is required to run the program. This must be used after logging on to the system as an administrator account on Windows XP, Windows Server 2003, and other operating systems. In Windows Vista or Windows 7 or above, the program may fail to run due to UAC (User Account Control) problems. After all, Windows Vista and above systems further increase system security, further restrictions are imposed on operations on sensitive data such as the registry. To make the program run properly, right-click the program and on the compatibility tab, select "run this program as administrator ".

Alternatively, right-click the program and choose run as administrator ".

Another method is to use the app. manifest file to declare the permissions required for running the program in advance, so as to avoid control blocking of Windows UAC. To do this, right-click the project USBViewer, select "properties"-"security", and select "enable ClickOnce Security Settings ",

In this case, an app. manifest file (under the Property folder of the project) is automatically added to the project. open the file and find

Replace asInvoker with requireAdministrator,

Save the compilation project. Note: Before saving the compilation project, deselect "enable ClickOnce Security Settings" in project security. Otherwise, an error occurs during compilation (uncheck this option and the generated app. manifest file will not be deleted ). In this way, the program runs automatically as administrator.

After the permission problem is solved, copy the service program usbcleaner.exeof the deleted USB storage device to the USB viewer.exe.pdf folder and run USB viewer.exe. The result is as follows:

Execute the delete operation. The System Service List displays the service named USB cleaner:

Check its properties. It is indeed a service that performs the Registry deletion operation.

Click "exit", wait for the program to uninstall the service, and then view the system service list again, and find that the USB cleaner service has been uninstalled. Check the USB viewer.exefile folder and you will find two more files, USB cleanerlog.txt, which is the log file for deletion:

Another file, USBCleaner. InstallLog, is a log file generated when you install and uninstall the service. You can open it and view the content.

Section 5 Summary

Through this C # WindowsForm programming exercise, I became more familiar with the use of C #, and had a better understanding of registry operations and Windows service installation and uninstallation, at the same time, I sorted out the relevant knowledge to improve the programming level. (The solution file involved in this article has been compressed into a compressed file in RAR format for download. Download link: http://download.csdn.net/detail/metaphysis/6864213 ).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.