3

要加载 .dic 和 .aff 文件,我们使用以下代码。

 using (var hunspell = new Hunspell("en.aff", "en.dic"))
                {

                }

但是,如果使用 c# 作为资源嵌入,如何加载 NHunspell .dic 和 .aff 文件?

我正在尝试以下代码,但它非常慢。

using (var hunspell = new Hunspell(GetBytes(Properties.Resources.enaff), GetBytes(Properties.Resources.endic)))
                {

                }
static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
4

1 回答 1

3

假设您在其中一个应用程序程序集中将这两个文件作为嵌入式资源,例如:

  • 大会名称:MyApp.MyAssemblyWithResources
  • aff 文件的资源名称:MyApp.MyAssemblyWithResources.AffFile
  • dict文件的资源名称:MyApp.MyAssemblyWithResources.DictFile

然后加载并使用它们,请执行以下操作:

// These buffers will receive the content of the embedded resource files.
byte[] affFileBytes = null;
byte[] dictFileBytes = null;

// We have to load the resource files from the assembly in which they were embedded.
var myAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.Equals("MyApp.MyAssemblyWithResources")).Single();

// To do so we need to get a stream that allows us to read them.
using (var affResourceStream = myAssembly.GetManifestResourceStream("MyApp.MyAssemblyWithResources.AffFile"))
using (var dictResourceStream = myAssembly.GetManifestResourceStream("MyApp.MyAssemblyWithResources.DictFile"))
{
    // Now we know their size and can allocate room for the buffer.
    affFileBytes = new byte[affResourceStream.Length];

    // And read them from the resource stream into the buffer.
    affResourceStream.Read(affFileBytes, 0, affFileBytes.Length);

    // Same thing for the dictionary file.
    dictFileBytes = new byte[dictResourceStream.Length];
    dictResourceStream.Read(dictFileBytes, 0, dictFileBytes.Length);
}

// Now the loaded buffers can be used for the NHunspell instance.
using (var hunspell = new Hunspell(affFileBytes, dictFileBytes))
{
    // Do stuff with spellin and gramma.
}
于 2013-08-17T03:17:07.883 回答