views:

1582

answers:

6

What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.

Or, if there's a better way to unit test against the registry...

thanks.

+2  A: 

I looked into it by checking out my file associations.

It seems that a .reg file is just called as the first parameter to the regedit.exe executable on Windows.

So you can just say regedit.exe "mytest.reg". What I'm not sure of is how to get rid of the dialog box that pops up that asks for your confirmation.

Javache
A: 

Use the Win32 API function ShellExecute() or ShellExecuteEx(). If the comment is 'open' it should merge the .reg file. I haven't tested it, but it should work.

jmatthias
+1  A: 

yeah, thought of both of those.... but then how do you remove the entries? I don't think regedit command line provides that functionality.

I think I'm going to go with the approach of just adding the keys via the usual registry API's, then remove them the same way.

Unless some better way comes along.

scottmarlowe
+6  A: 

It is possible to remove registry keys using a .reg file, although I'm not sure how well it's documented. Here's how:

REGEDIT4

[-HKEY_CURRENT_USER\Software\<otherpath>]

The - in front of the key name tells Regedit that you want to remove the key.

To run this silently, type:

regedit /s "myfile.reg"
Matt Dillard
A: 

One of the most frustrating things about writing unit tests is dealing with dependencies. One of the greatest things about Test-Driven Development is that it produces code that is decoupled from its dependencies. Cool, huh?

When I find myself asking questions like this one, I look for ways to decouple the code I'm writing from the dependency. Separate out the reading of the registry from the complexity that you'd like to test.

Jay Bazuzi
+3  A: 

If you're shelling out, I'd use the reg command (details below). If you can tell us what language you're working with, we could provide language specific code.

C:>reg /?

REG Operation [Parameter List]

Operation [ QUERY | ADD | DELETE | COPY | SAVE | LOAD | UNLOAD | RESTORE | COMPARE | EXPORT | IMPORT | FLAGS ]

Return Code: (Except for REG COMPARE)

0 - Successful 1 - Failed

For help on a specific operation type:

REG ADD /? REG DELETE /? [snipped]

Jon Galloway