Click here to Skip to main content
Click here to Skip to main content

NHunspell - Hunspell for the .NET platform

, 21 Jul 2014 LGPL3
Rate this:
Please Sign up or sign in to vote.
The spell checking and hyphenation features of OpenOffice for the .NET platform.


I was looking for a good spell checker and hyphenation library for .NET, and I found the free (LGPL licensed) Hunspell spell checker and Hyphen libraries used in OpenOffice. Hunspell wasn't available for the .NET platform. So, I decided to write a wrapper/port. It is quite nice that a lot of the OpenOffice dictionaries are LGPL licensed too and can be used in proprietary applications.

Interop code to the native Hunspell functions

I used Managed C++ to write the wrapper/port, because I could use the original source code of Hunspell and Hyphen. It was quite nice to write the interop code between managed classes and the unmanaged Hunspell and Hyphen libraries. The original source code is almost unchanged, so that new versions of Hunspell or Hyphen can be easily adopted. Hunspell and Hyphen use unmanaged memory functions, so I had to implement the IDisposable interface and used this pattern to free unmanaged memory early.

Because Hunspell uses UTF8 coding, I had to provide conversion functions from/to UTF8:

char * NHunspell::MarshalHelper::AllocUTF8FromString(String ^value)
    array<Byte> ^ byteArray = Encoding::UTF8->GetBytes(value);
    int size = Marshal::SizeOf(byteArray[0]) * (byteArray->Length + 1);
    IntPtr buffer = Marshal::AllocHGlobal(size);
    Marshal::Copy(byteArray, 0, buffer, byteArray->Length);
    Marshal::WriteByte(buffer, size - 1, 0);
    return (char *) buffer.ToPointer();

String ^ NHunspell::MarshalHelper::AllocStringFromUTF8( char * value )
    int size = strlen(value);
    array<Byte> ^ byteArray = gcnew array<Byte>(size);
    Marshal::Copy(IntPtr(value), byteArray, 0, size);
    return Encoding::UTF8->GetString(byteArray);

Another big thing is to handle the unmanaged memory. I implement destructors and finalizers to deal with this:


    if( handle != 0 )
        delete handle;
        handle = 0;

bool NHunspell::Hunspell::IsDisposed::get()
    return handle == 0;

NHunspell spell checking and hyphenation sample

This is a short demo of how to use NHunspell for spell checking, suggestions, and hyphenation:

Console.WriteLine("NHunspell functions and classes demo");

Console.WriteLine("Spell Check with with Hunspell");

// Important: Due to the fact Hunspell will use unmanaged memory
// you have to serve the IDisposable pattern
// In this block of code this is be done
// by a using block. But you can also call hunspell.Dispose()
using (Hunspell hunspell = new Hunspell("en_us.aff", "en_us.dic"))
    Console.WriteLine("Check if the word 'Recommendation' is spelled correct"); 
    bool correct = hunspell.Spell("Recommendation");
    Console.WriteLine("Recommendation is spelled " + 
              (correct ? "correct" : "not correct"));

    Console.WriteLine("Make suggestions for the word 'Recommendatio'");
    List<string> suggestions = hunspell.Suggest("Recommendatio");
    Console.WriteLine("There are " + suggestions.Count.ToString() + 
                      " suggestions" );
    foreach (string suggestion in suggestions)
        Console.WriteLine("Suggestion is: " + suggestion );

Console.WriteLine("Hyphenation with Hyph");

// Important: Due to the fact Hyphen will use unmanaged
// memory you have to serve the IDisposable pattern
// In this block of code this is be done by a using block.
// But you can also call hyphen.Dispose()
using (Hyphen hyphen = new Hyphen("hyph_en_us.dic"))
    Console.WriteLine("Get the hyphenation of the word 'Recommendation'"); 
    HyphenResult hyphenated = hyphen.Hyphenate("Recommendation");
    Console.WriteLine("'Recommendation' is hyphenated as: " + 
                      hyphenated.HyphenatedWord ); 

Console.WriteLine("Press any key to continue...");

Because Hunspell is native C++ code, you must include the correct assembly for your platform. On x86 platforms (32 bit), use the NHunspell.dll from the X86 folder. On X64 platforms, use the NHunspell.dll from the X64 folder.


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


About the Author

I'm working on a new project called Crawler-Lib. It is a generalized back-end processing and hosting framework for Microsoft .NET and Mono. Please take a look at it:
Crawler-Lib Homepage
Crawler-Lib Blog
Crawler-Lib YouTube Channel
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

QuestionHyphenation priority PinmemberYves Goergen27-Jan-15 5:04 
QuestionCan we get grammar suggestions using this library? PinmemberNitin Sawant29-Nov-12 19:56 
AnswerRe: Can we get grammar suggestions using this library? [modified] PinmemberThomas Maierhofer18-Mar-13 12:32 
QuestionForm Resize issue PinmemberScott Logan11-Nov-11 2:07 
QuestionStrange hang Pinmemberjarofkla15-Dec-10 5:53 
GeneralAFF File not found Pinmemberhemaprathima24-Nov-10 21:01 
General"Stack empty" error every now and then with v0.9.6 PinmemberRune Jacobsen13-Oct-10 21:24 
GeneralRe: "Stack empty" error every now and then with v0.9.6 [modified] PinmemberThomas Maierhofer14-Oct-10 4:37 
GeneralRe: "Stack empty" error every now and then with v0.9.6 PinmemberRune Jacobsen18-Oct-10 1:33 
Hi Thomas, thanks for your reply.
This is an ASP.NET MVC application. For context; I have a specific controller called SpellController that handles all spell requests. In this particular site, only administrators can edit text and are affected by spelling - so this controller only exists when an admin is logged on and doing some editing.
Further, the site supports three languages - english, norwegian and danish. Each page being edited has an indicator of the language, so that I can spell check properly.
Before you replied to my question, I actually didn't use the SpellFactory at all. I don't remember why, but what I ended up doing was creating three LanguageConfig objects, then created a SpellEngine and did an _engine.AddLanguage with the config for each language. Spellchecking was done via this method:
return _engine[code].Spell(word);
Where code was the language code given in the LanguageConfig objects.
This works very well, except for the occasional exception as stated above.
However, because of your suggestion, I also went ahead and added a way to do this with three SpellFactory objects instead of the single SpellEngine. I used the same LanguageConfig except I had to set the "Processors" property (I set it to 2 just for fun, didn't research a proper value yet).
Now I get the exception on either the first request, or soon after, after a seemingly random amount of words (the controller calls this spell method for each word in the article being edited).
Here is an example of how I do it for the norwegian language:
            var noConfig = new LanguageConfig
                LanguageCode = "no",
                HunspellAffFile = _appPath + @"\Dictionaries\nb_NO.aff",
                HunspellDictFile = _appPath + @"\Dictionaries\nb_NO.dic",
                HunspellKey = "",
                Processors = 2
            _norskFactory = new SpellFactory(noConfig);
(I hope the formatting for this is sane)
Then in another method:
            var factory = FactoryFromLanguage(language);
            return factory.Spell(word);
The FactoryFromLanguage() methods just gets the correct SpellFactory() for the given language code.
The first time I get an exception, I get a NullReferenceException (Object reference not set to an instance of an object) on the factory.Spell(string) method. There is no inner exception. The factory object is not null, so there must be something inside it.
If I now refresh the page that does the spellchecking via ajax, I get a different exception in the same place. InvalidOperationException with a message "Stack empty", no inner exception.
If you need any further information from me, please let me know, I am eager to figure this out. Again, thank you very much for the help!
GeneralRe: "Stack empty" error every now and then with v0.9.6 [modified] PinmemberThomas Maierhofer18-Oct-10 1:52 
GeneralRe: "Stack empty" error every now and then with v0.9.6 PinmemberRune Jacobsen18-Oct-10 2:03 
GeneralNHunspell Version 0.9.5 released [modified] PinmemberThomas Maierhofer19-Jul-10 0:05 
GeneralProblem loading the native DLL PinmemberRune Jacobsen1-Jul-10 2:08 
GeneralRe: Problem loading the native DLL [modified] PinmemberThomas Maierhofer18-Jul-10 23:50 
GeneralRe: Problem loading the native DLL PinmemberRune Jacobsen11-Aug-10 0:41 
QuestionSom question that i have PinmemberViki Vic1-Jun-10 23:34 
AnswerRe: Som question that i have [modified] PinmemberThomas Maierhofer18-Jul-10 23:59 
GeneralProblem exporting solution Pinmemberyunou13-May-10 13:59 
GeneralRe: Problem exporting solution PinmemberThomas Maierhofer19-Jul-10 0:01 
GeneralNot Working in Windows Form Pinmembermouthpiec7-Mar-10 7:29 
GeneralRe: Not Working in Windows Form Pinmembermouthpiec7-Mar-10 7:47 
GeneralRe: Not Working in Windows Form Pinmembermouthpiec7-Mar-10 8:47 
GeneralHunspell class Add method not working Pinmembermrmans0n23-Feb-10 9:20 
GeneralRe: Hunspell class Add method not working PinmemberJBoinker2-Jun-10 16:02 
GeneralRe: Hunspell class Add method not working [modified] PinmemberThomas Maierhofer19-Jul-10 0:02 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150129.1 | Last Updated 21 Jul 2014
Article Copyright 2009 by Thomas Maierhofer (Tom)
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid