2012-08-06 149 views
1

我試圖 「測試」 一詞翻譯,
我的代碼:VB.net使用谷歌翻譯

Imports Google.API.Translate 

Public Class Form1 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
     TextBox1.Text = "test" 
     Dim gtras As New TranslateClient("MY API KEY") 
     Label1.Text = gtras.Translate(TextBox1.Text, Language.English, Language.Hebrew, TranslateFormat.Text) 

    End Sub 
End Class 

的例外是:

Attempt by method 'Google_Translator.Form1.Button1_Click(System.Object, System.EventArgs)' to access method 'Google.API.Enumeration.op_Implicit(Google.API.Enumeration)' failed. 
+0

聽起來好像Google API的路徑設置不正確。老實說,這只是一個猜測(因此是一個評論,而不是一個建議的答案)。 – sacredfaith 2012-08-06 14:05:25

+0

此外,請確保您的項目所針對的.Net版本與您正在使用的Google API的.Net版本相匹配。 – sacredfaith 2012-08-06 14:08:15

+0

@sacredfaith爲什麼要改變.Net框架有所作爲? – 2012-08-07 04:13:51

回答

0

此代碼的工作非常好:

Imports Newtonsoft.Json 
Imports Newtonsoft.Json.Linq 
Imports System 
Imports System.Net 
Imports System.Text 
Imports System.Web 
Public Class Form1 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    MsgBox(gtranslate(TextBox1.Text, "it", "en"))'From italian to english, of course you can change it 
End Sub 

Public Shared Function gtranslate(ByVal inputtext As String, ByVal fromlangid As String, ByVal tolangid As String) As String 
    inputtext = HttpUtility.HtmlAttributeEncode(inputtext) 
    Dim step1 As New WebClient 
    Dim step2 As String = step1.DownloadString("https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=" & tolangid & "&hl=" & fromlangid & "&dt=t&dt=bd&dj=1&source=icon&q=" & inputtext) 
    Dim step3 As Newtonsoft.Json.Linq.JObject = JObject.Parse(step2) 
    Dim step4 As String = step3.SelectToken("sentences[0]").SelectToken("trans").ToString() 
    Return step4 
End Function 
End Class 

DLL庫「Newtonsoft.JSON」可從their website,如果你得到一些錯誤,以「HttpUtility」,在添加添加引用「的System.Web」參考窗口 - > .net選項卡