Serializing CStringList in the registry

The registry is an ideal place to store information about your application. Using a key and a Value Name you can easily store and retrieve Value Data once you get a hang of the registry APIs.

I recently encountered a scenario where I needed to store a list of strings in the registry. Typically, that would involve ::RegOpenKeyEx(key) followed by a series of ::RegSetValueEx(ValueName, ValueData). Unfortunately, I didn't have any Value Names for the list of strings to store. In other words, if I have 5 strings to write into the registry, I would need to generate 5 different Value Names to uniquely identify each string. Here's what the registry would look like:

Key:
SOFTWARE\Commpany\App\strings

Value Name and Value Data:
a = "string1"
b = "string2"
c = "string3"
d = "string4"
e = "string5"

The downside of this technique is the excessive number of Value Names, and the pseudo-random generation of those names. My original need of storing N strings would be better served by specifying only one Value Name along with a string list.

The technique I implemented consists of serializing a CStringList using MFCs CMemFile, CArchive and the registry's REG_BINARY data type. The registry is not the appropriate place to store massive amounts of data, and anything over 2K should be stored as a separate file outside the registry. Therefore, I placed a hard coded limit of 4096 bytes for the string list.

The code was tested using Microsoft Visual C++ 5.0sp3 under Windows 95.

// skip registry key opening sequence for clarity
const INT nSIZE = 4096;
DWORD dwType;
DWORD dwData  = nSIZE;
BYTE* bData   = (BYTE*)::calloc(nSIZE, sizeof(TCHAR));
ASSERT(bData);

const LONG retValue = ::RegQueryValueEx(hKey, pszValueName, NULL, &dwType,
bData, &dwData);

if(retValue == ERROR_SUCCESS and REG_BINARY == dwType){
ASSERT(dwData < nSIZE);
try{
  // Read
  CMemFile file(bData, nSIZE);
  CArchive ar(&file, CArchive::load);
  ar.m_bForceFlat = FALSE;
  ASSERT( ar.IsLoading() );
  CStringList myList;
  ASSERT( myList.IsSerializable() );
  myList.Serialize(ar);
  ar.Close();
  file.Close();

  myList.AddTail("Another string!");

  // Write
  file.Attach(bData, nSIZE, 16);
  CArchive ar2(&file, CArchive::store);
  ASSERT(myList.IsSerializable());
  myList.Serialize(ar);
  ar2.Close();
  const DWORD dwLen = file.GetLength();
  ASSERT(dwLen < nSIZE);
  ::RegSetValueEx(hKey, pszValueName, 0, REG_BINARY, file.Detach(), dwLen);
}
catch(CMemoryException* e){
  e->ReportError();
  e->Delete();
}
catch(CArchiveException* e){
  e->ReportError();
  e->Delete();
}
catch(CFileException* e){
  e->ReportError();
  e->Delete();
}
if(bData) free(bData); bData = NULL;
}



Comments

  • Conscious and innovative shape despatch clothes with unforgettable pockets designed to arrangement outdoors you hand-picked the uncut with you.

    Posted by koltchuwn on 04/17/2013 09:16am

    We wanted to overcharge some habits to highlight some of the talented shops [url=http://www.hollistercovfrance.fr]hollister[/url] draining there that come into supported ADHERE TO championing so long and are doing likeable things in their parts of the motherland or the in the seventh fortunate [url=http://www.abercrombiesfrancevparisu.fr]abercrombie france[/url]. There are aristocratic untrammelled retailers commission there, innumerable of which are cultivating trends once they leave the larger market. It's so energetic with a view our ticket and our retailers to [url=http://www.airjordanfrpaschera.fr]air jordan pas cher[/url] constantly be evolving. We all have so much tendentiousness representing the assiduity we craft in and the undistinguished detached of pushing the industry forward. Enough jibba jabba, today's light up is on FUNDAMENTAL PURVEY CO in Richmond, [url=http://www.abercrombiefrancersoldes.fr]abercrombie[/url] VA. I secure recently fallen in love with the name brand SkunkFunk which [url=http://www.airjordanspasuchera.fr]air jordan pas cher[/url] features on style-is.co.uk and has some wild sustainable invent in renowned the dresses which I from been lusting atop of on a joint foundation [url=http://www.hollisterfrancevmagusin.fr]hollister[/url]. I couldn’t maintain my unforeseen when I was asked away a retailer to reassess a sherd of sustainable fashion. Of improvement advance I elect a SkunkFunk rebuke which arrived today. It [url=http://www.abercrombiexandfitchuke.co.uk]abercrombie[/url] was true mastery than I expected, can’t stick circa to allot extraordinarily a blink [url=http://www.monclerfranceumagasinsfr.com]doudoune moncler[/url]! But in November, we each had a opportunity to earn a take care flinch from and look [url=http://www.karenmillenoutlet4s.co.uk]karen millen outlet[/url] at things from a unique perspective. We had been in so intensely, plugging away, racing on to the next device that we hadn’t enchanted the schedule to look up [url=http://www.michaelukorsua.com]michael kors[/url] and petition ourselves what we definitely wanted.We’ve dedicated two and a half years to creating a hightail it and a commodity that exceeded our (wildest) expectations. We’ve skilled more than we yet soup噊n [url=http://www.hollisterucoboutiques.fr]hollister france[/url] possible. We’ve met awe-inspiring people and made irredeemable connections. We’ve discovered a passion championing something we didn’t be familiar with we had.But with all of this intumescence, we’ve recently realized that rdeveloping garments [url=http://www.louboutinpascher5k.fr]louboutin pas cher[/url] is no longer something we desire after, or be purposive of we precondition, to work for what we were meant to do.

    Reply
  • A consulting engineering contour specializes in composite materials, FRP engineering and perpetuating

    Posted by carpitzsc on 04/16/2013 12:21am

    I acquire a handful places in burgh I unquestionably like and a handful spots [url=http://www.hollistercorfrance.fr]hollister france[/url] on all sides the beneficence I would concerned to, accepted the opportunity. It's a wearying verse to rejoinder because so much of a extreme assail go off overboard is dependent on the [url=http://www.abercrombiesfrancevparise.fr]abercrombie france[/url] bind and experience. I be captivated by sharing a collation with appropriate friends, it's something I often diminish on about. A to a cyclopean scale vital stroke, but a indigence against everyone. If you're eternally in Richmond [url=http://www.airjordanfrpaschere.fr]air jordan pas cher[/url] you should crack at Mamma Zu, they do incredibly authentic Italian in a bloody unassuming space. Or you can unexceptionally upstanding cortege throughout the corner from our inventory and sup a tremendous burger and fries at Can Can. They also make some dangerous things to coating it down. Quest of the sake of things being what they are, this innovative bra is also thriving to [url=http://www.abercrombieufrancersoldes.fr]abercrombie france[/url] inducement wonders subordinate to transitional jersey dresses. As the design gained aggregation invite—in profit occurrence, [url=http://www.airjordanspasuchere.fr]air jordan[/url] it was the law haircut in the widely distributed Sears post layout catalog during the ’20s—more sophisticated variations developed. The finger ruffle [url=http://www.hollisterfrancevmagesin.fr]hollister[/url] (S-shaped waves made using fingers and a comb), the Marcel (also wavy, using the newly invented frying curling iron), shingle bob (tapered, and exposing the promote of the [url=http://www.abercrombievandfitchuks.co.uk]abercrombie[/url] neck) and Eton crop (the shortest of the bobs and popularized during Josephine Baker) added fit as a fiddle to the indelicate cut. Be warned: Some chic styles weren’t [url=http://www.monclerfrancermagasinsfr.fr]moncler[/url] as a specific for the sake of the unclear of heart. A medical voice, the Shingle Headache, was described as a fettle of neuralgia caused next to the swift departure of locks from the unpredictable nape of the neck, or in fact getting your mane cut to pieces in a shingle bob. Don’t like your legs? Do you sense that your legs are too short? Too rotund [url=http://www.airjordanzchaussuren.com]air jordan[/url]? Too white? Whatever your mind, you don’t like your legs and don’t wish anyone else to look at them when wearing a deck into the open air, shorts, or a skirt [url=http://www.michaelukorsua.com]michael kors outlet[/url]. No can of worms! A ruffled pinnacle approve set in order the problem. Be steady to heart all the discomfort on your upper half and manifest a in black, unassuming bottom.Got an hourglass figure? If so, fortuitous you! While you [url=http://www.hollisterucoboutiquer.fr]hollister pas cher[/url] can positively have on anything you crave, you should still to out of ruffles. You don’t after exchange for to survive ruffles on your curves to throw up them touched in the gourd proportion. In prejudice to, damage them here your sleeves, collar, or [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin[/url] prat hem.

    Reply
  • Returns the second place was June Stuart Weitzman shoe heel needle metal , Monitoring low -quality Jimmy Choo sandals June Jordan

    Posted by Vetriatszy on 03/15/2013 09:54am

    Abercrombie fitch conversion points take a look at thousands involving although helping the latest fashions; gals associated with commonly notice it in runways in addition, on a person's vast popular choice fashion channels having with regards to their beauties in the dresses they can indeed be about. Rachel Zoe untamed hair beautician Rachel Zoe's acquirer list may perhaps possibly look over perhaps a who's who relevant to Hollywood's considerable the women--Cameron Diaz, Hathaway simply because catwoman and perhaps Demi Moore are simply only a few--yet unfortunately let's not pretend, Zoe she is has gotten equally as popular due to private special type. Zoe's fondness regarding heavens-High high heels, retro-fabricated Grecian robes in addition,yet piled-after neck laces would have rendered your loved one's an approach skin image. the lady htc bravo certainty reveal the fact this particular Rachel Zoe project offers available professionals sort of deciding upon for several further closet prospects, and consequently as your ex QVC vogue complete established a last year, partizans are actually able to copy they creator design cheaper. Lauren hardwood a traditional depth machine, Lauren shrub (she will be arrived in the time of Tommy Hilfiger and also Abercrombie Fitch advertising campaigns) would be probably any kind of ecosystem-mode trailblazer. nowadays when compared with 3 hundred retains in america of the united states. Abercrombie Fitch out of providers recommends garments effectively additional items and this can be alleged to occur at a lower price than usual. much of about the web extensive manufacturers who scale back the value and then sell on the manufacturer to assist you to fascinated people. savoury premium will probably be an created name brand. less expensive moist fashion jacket in order to matches, d-shirts, browse around these guys pockets, lingerie, and additionally excess for example bags, wrist watches, colorings are for sale to customers in online world distributors but brokers. clients in this article inexpensive cost passes upgrade. motivating in full price plans apart from companies are glad to purchase or even some precious varieties and so possess the perfect vogue labeling happily! if you are more of the trousers male, have the Rollins toned from the poor polish glance. in the end you believe inside the house within 100 p. c,nought per cent cotton items. it's rather a lanky back of the leg very few trousers utilizing a considerable dim component. The ticker definitely is mounted inside regards to right-give local area life's savings. you see, the Abercrombie and after that Fitch recurrent stitching are in the rear banking account. this kind of t-shirts usually are gradually getting flawlessly created for persons. from the event you explain the similarity about the regulars, you're going to go to remember young girls let alone men tend to be more hoping to possess you can find t-shirt of the identity, with regards to they're betting that no one other good seller very well offer up these items these sort of superior, exceptional also competitive t-t-shirts, which match perfectly on particular individuality. any time you will procedure within it a number of the dealers connected with Abercrombie Fitch, as well as you have been in a flash likely to be tempted within the tidily exhibited each and every Abercrombie t-clothing. you probably have some factors with reference to your very own health or the healthiness of your son, it is best to consult with a physician also known as added physician. impress study the privacy in addition to relation to Use in advance of when with this site. their technique site exhibits statement of being bound over the terms of Use

    Reply
  • Registry key

    Posted by Legacy on 05/14/2003 12:00am

    Originally posted by: Bhargavi

    It is nice we have tested code in C++. Can we apply same logic in Java??

    Reply
  • Ah it's not true you don't need more than one value :(

    Posted by Legacy on 03/10/2000 12:00am

    Originally posted by: Tobias Sch�nherr

    When you look at the docs you'll see that there's a value type REG_MULTI_SZ. It defines a registry key that stores strings separated with 00.
    
    

    Here's my small sample code

    void CRegistry::GetStringList(LPCTSTR SubKey, LPCTSTR Value, CStringList &SL)
    {
    HKEY hKey;
    if(RegOpenKeyEx(m_hKey, SubKey,0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
    {
    DWORD ValueType;
    if(RegQueryValueEx(hKey, Value, NULL, &ValueType, NULL, NULL) == ERROR_SUCCESS)
    {
    if(ValueType == REG_MULTI_SZ)
    {
    char ca[64000];
    DWORD BufLen = 64000;
    if(RegQueryValueEx(hKey, Value, NULL, NULL, NULL, &BufLen) == ERROR_SUCCESS)
    {
    if(BufLen > 1)
    {
    if(RegQueryValueEx(hKey, Value, NULL, NULL, (LPBYTE)ca, &BufLen) == ERROR_SUCCESS)
    {
    unsigned int begin = 0;
    for(unsigned int ipos=0; ipos<64000; ipos++)
    {
    if(ca[ipos] == '\0')
    {
    CString s;
    for(unsigned int ipos2=begin; ipos2 < ipos; ipos2++)
    {
    s += ca[ipos2];
    }
    SL.AddTail(s);
    begin = ipos+1;
    if(ca[begin] == '\0') break;
    }
    }
    }
    }
    }
    }
    }
    RegCloseKey(hKey);
    }
    }

    void CRegistry::PutStringList(LPCTSTR SubKey, LPCTSTR Value, CStringList &SL)
    {
    HKEY hKey;

    if(RegCreateKeyEx(m_hKey, SubKey, 0, _T(""),
    REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS)
    {
    CString String;

    for(POSITION pos = SL.GetHeadPosition(); pos != NULL; )
    {
    String += SL.GetAt(pos);
    String += '\0';

    SL.GetNext(pos);
    }
    String += '\0';

    RegSetValueEx(hKey, Value, 0, REG_MULTI_SZ, (LPBYTE)(LPCTSTR)String, String.GetLength());
    RegCloseKey(hKey);
    }
    }

    By Tobias ;)

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • In this webinar, IDC featured speaker Steve Conway, Vice President of High Performance Computing, will present an update on the global x86 HPC cluster market. The presentation will include IDC's five-year forecast for the medium- to large-scale technical computing and data analysis emerging markets by systems, processors and application middleware. Cray's featured speaker, John Lee, Vice President of Cray Cluster Advanced Technology Systems, will present the new Cray® CS400™ cluster series based on …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds