2013-08-17 150 views
2

要加載.dic和.aff文件,我們使用下面的代碼。從資源加載.dic和.aff文件?

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

       } 

但是,如果加載NHunspell .dic和.aff文件,如果嵌入資源使用c#?

我正在嘗試下面的代碼,但它是該死的緩慢。

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; 
    } 

回答

3

假設你在你的應用程序組件一個有兩個文件作爲嵌入的資源,例如:

  • 大會名稱:該 AFF文件的MyApp.MyAssemblyWithResources
  • 資源名稱:MyApp.MyAssemblyWithResources.AffFile
  • 資源名稱 字典文件: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. 
} 
+0

我曾在我的問題也做同樣的事情進行一些編輯。但問題是現在拼寫檢查速度很慢。爲什麼? – jeff

+0

其中一個原因可能是您正在使用的代碼中,您正在將二進制文件作爲字符串加載,所以這可能是問題所在。您使用過的文件名參數的'Hunspell'代碼(參見http://nhunspell.svn.sourceforge.net/viewvc/nhunspell/trunk/NHunspell/Hunspell.cs?revision=87&view=markup)構造函數也只是讀取文件的字節,然後用字節緩衝區加載它,完全相同的代碼。所以如果它變慢了,那麼字節緩衝區的內容肯定有問題。 – Alex

+0

你的代碼工作正常。感謝您解決我的問題 – jeff