Click here to Skip to main content
15,891,597 members
Articles / Programming Languages / C#
Article

Import/Export registry sections as XML

Rate me:
Please Sign up or sign in to vote.
4.58/5 (11 votes)
8 Feb 20051 min read 99.2K   4.1K   32   18
Allows for the import and export of registry sections as XML.

Sample screenshot

Introduction

If you need to backup and restore sections of the registry using C#, then these classes will be a big help. I have needed to do so in spyware and backup/restore applications for third party products. In C++, I have used the code from Stephane Rodriguez's article here. These classes provide a conversion from the main classes he developed.

Where It Got Tricky

One of the nice things about his routines is that they handle creation of all registry key types. DWORD with both little and big Endian, links, multi sz, resource lists, etc. I quickly realized that the base registry classes did not handle creation of entries of these types. So I created DllImport for each of the registry methods needed.

C#
[DllImport("advapi32.dll", EntryPoint="RegOpenKey")] public static extern 
   int RegOpenKeyA(int hKey, string lpSubKey, ref int phkResult);

[DllImport("advapi32.dll")] public static extern 
   int RegCloseKey(int hKey);

[DllImport("advapi32.dll", EntryPoint="RegQueryInfoKey")] public static extern 
   int RegQueryInfoKeyA(int hKey, string lpClass, 
   ref int lpcbClass, int lpReserved, 
   ref int lpcSubKeys, ref int lpcbMaxSubKeyLen, 
   ref int lpcbMaxClassLen, ref int lpcValues, 
   ref int lpcbMaxValueNameLen, ref int lpcbMaxValueLen, 
   ref int lpcbSecurityDescriptor, 
   ref FILETIME lpftLastWriteTime);

[DllImport("advapi32.dll", EntryPoint="RegEnumValue")] public static extern 
   int RegEnumValueA(int hKey, int dwIndex, 
   ref byte lpValueName, ref int lpcbValueName, 
   int lpReserved, ref int lpType, ref byte lpData, ref int lpcbData);

[DllImport("advapi32.dll", EntryPoint="RegEnumKeyEx")] public static extern 
   int RegEnumKeyExA(int hKey, int dwIndex, 
   ref byte lpName, ref int lpcbName, int lpReserved, 
   string lpClass, ref int lpcbClass, ref FILETIME lpftLastWriteTime);

[DllImport("advapi32.dll", EntryPoint="RegSetValueEx")] public static extern 
   int RegSetValueExA(int hKey, string lpSubKey, 
   int reserved, int dwType, ref byte lpData, int cbData);

I also changed the UTF8 encoding classes to use C# built in Encoding classes, string routines, etc. I left it using the XML routines he had created as opposed to using the ones built in to C# for sake of time.

Backup A Registry Section

In the end, it provides a very easy way to backup a registry section to a file. You just specify the section (you can use a string pulled from regedit) and then tell it to create the file. This is really great as well as you could load the XML back in and use XPath classes or other tools to analyze it.

C#
string strRegistrySection = 
   "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

if (xmlRegistry.keyExists(strRegistrySection))
{
  xmlWriter w = new xmlWriter(); 
  xmlRegistry xmlReg = new xmlRegistry();
  w.open( textBoxFileName.Text );
  xmlElement wroot = new xmlElement(xmlRegistry.XML_ROOT);
  wroot.write(w,1,false,true);
  xmlReg.saveAsXml( w, false, strRegistrySection, "");
  wroot.writeClosingTag(w,-1,false,true);
  w.close();

}

Restore A Registry Section

Restoring a registry section is even easier.

C#
xmlReader xmlReader = new xmlReader();
xmlRegistry xmlReg = new xmlRegistry();

xmlReg.loadAsXml(xmlReader, textBoxFileName.Text );

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Mexico Mexico
Private consultant living in sunny Mazatlan, Mexico. I been developing commerical applications for over 15 years in C, C++ and Java. I am very excited about working with C# and web services.

I moved down to Mexico and have been freelancing ever since. Nothing like working on the beach while drinking a margarita... except I keep getting sand in my laptop.

Comments and Discussions

 
QuestionAny change there is an enhancement possible? Pin
Niteowls4-Oct-14 4:23
Niteowls4-Oct-14 4:23 
QuestionOkay to modify/rehash? Pin
The|Aaaron|Mals8-Apr-14 22:01
The|Aaaron|Mals8-Apr-14 22:01 
SuggestionPerformance issues Pin
Midax14-Nov-12 5:47
Midax14-Nov-12 5:47 
GeneralMy vote of 5 Pin
Midax14-Nov-12 5:44
Midax14-Nov-12 5:44 
QuestionIndex was outside the bounds of the array. Pin
Funnyboy26-Aug-12 19:10
Funnyboy26-Aug-12 19:10 
QuestionRegarding license Pin
ub3rst4r14-Dec-10 20:08
ub3rst4r14-Dec-10 20:08 
QuestionHow to get rid of the unnecessary null terminators on REG_SZ key values Pin
Mark Hemingway4-Mar-10 0:53
Mark Hemingway4-Mar-10 0:53 
Generalgiving exception when i tried running the code in vs 2008 Pin
Geetha_Kumari12-Nov-08 0:49
Geetha_Kumari12-Nov-08 0:49 
GeneralRe: giving exception when i tried running the code in vs 2008 Pin
gardia19-Aug-09 3:08
gardia19-Aug-09 3:08 
GeneralRe: giving exception when i tried running the code in vs 2008 Pin
franco nero10-Dec-09 11:27
franco nero10-Dec-09 11:27 
GeneralRe: giving exception when i tried running the code in vs 2008 Pin
boslbosl10-Feb-10 22:27
boslbosl10-Feb-10 22:27 
QuestionNot working on windows 64 bit Pin
Dev-Rama11-Jun-07 0:52
Dev-Rama11-Jun-07 0:52 
GeneralAnother way to import registry in C# Pin
mycsharpcorner6-Apr-07 7:26
mycsharpcorner6-Apr-07 7:26 
GeneralBugs/Ideas Pin
Eric Engler8-Nov-06 9:55
Eric Engler8-Nov-06 9:55 
This is a cool project and I don't want to sound like I'm whining. These are some points I wrote down, but I'm still happy with the author's work.

1) It tries to quote XML unsafe values, but it messes up sometimes.
For example, try to backup a string key value like this: test<red>
and it only quotes the first angle bracket:
<v name="test" value="Test<RED> ">
and it will restore the value wrongly.

Fix:
a) Find this:
else if (c=='<')
s += "<";

Add these lines after it:
else if (c == '>')
s += ">";

b) Find this:
while ( (nLt=s.IndexOf("<",0))>-1 )
s = s.Substring(0,nLt) + "<" + s.Substring(nLt+4);

Add these lines after it:
while ((nLt = s.IndexOf(">", 0)) > -1)
s = s.Substring(0, nLt) + ">" + s.Substring(nLt + 4);

2) Although it doesn't cause an operational problem, it embeds a
trailing null character value at the end of all string values
in the XML file. This works, but isn't true to the XML format.
Only text values should be in an XML file. Probably an easy fix.

3) It doesn't attempt to encode binary data in CDATA XML elements.
It only encodes the characters it thinks are unsafe, but if you
have binary values stuffed into a string in the registry (like
for an encrypted password), this won't give you valid XML output
file. It does seem to restore correctly - more testing is needed.

It's not easy to fix this without using CDATA for all values,
and this will produce an ugly, but valid, XML file. Maybe we
could test if there's any illegal char values and only use CDATA
if there are some during the backup. But then the restore has to
allow for the optional use of CDATA.

As an alternative to CDATA we could use Base64, but that's
ugly, too.

4) To eliminate some warnings in 2.0, replace FILETIME with
System.Runtime.InteropServices.ComTypes.FILETIME. I am guessing
there are other 2.0 safety issues like SAFEHANDLE that should be
investigated. This is obvoiously forgiveable since the author
used 1.1. Another poster here gave us an updated function that
uses SAFEHANDLE, but I didn't scrub the code looking for this
issue.

5) Try/Catch/Finally is not used agressively, but this is
forgiveable in a small demo like this. Whenever you use
unmanaged resources like the registry you have to ensure that
you always clean up, no matter what. The CLR can not free
open registry keys that may result from an exception.
QuestionImport/Export classes in .Net FW 2.0? Pin
D.Ecke20-Sep-06 3:20
D.Ecke20-Sep-06 3:20 
AnswerRe: Import/Export classes in .Net FW 2.0? Pin
Zylwee9-Oct-06 1:33
Zylwee9-Oct-06 1:33 
GeneralGreat Creation Pin
anksbond11-Apr-06 21:35
anksbond11-Apr-06 21:35 
GeneralRe: Same article on CP.. Pin
Sam DenHartog8-Feb-06 5:01
Sam DenHartog8-Feb-06 5:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.