Search code examples
xamarinxamarin.formsgoogle-cloud-platformxamarin.androidgoogle-translate

Not able to set the GOOGLE_APPLICATION_CREDENTIALS environment variable for Google.Cloud.Translation in xamarin forms


I'm trying to use Google.Cloud.Translation service of Google Cloud platform (GCP) for the translation of text in Xamarin forms. I want to translate my application from English to Arabic. I enabled the API. Created a json file from the Service account. Followed the step in the following url https://cloud.google.com/translate/docs/setup

But still when I try to set the GOOGLE_APPLICATION_CREDENTIALS I get exception-

Error reading credential file from location
C:/Users/xxx/Downloads/xxxx-280817-bedb566bfd11.json: Could not find a part of the path "/C:/Users/xxxx/Downloads/xxxx-280817-bedb566bfd11.json". Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS

I have tried numerous ways to fix this. This is my code:

System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS","C:/Users/xxx/Downloads/xx-280817-bedb566bfd11.json");
                    
TranslationClient client = TranslationClient.Create();

How can I fix this, so I can have translation of English to Arabic language in my Xamarin form?


Solution

  • Put your GOOGLE_APPLICATION_CREDENTIALS json file as EmbeddedResource and you can get yout path by this way

    <ItemGroup>
      <EmbeddedResource Include="_fonts/OpenSans.ttf" />
    </ItemGroup>
    

    to get the file path

    var assembly = typeof(MyLibrary.MyClass).GetTypeInfo().Assembly;
    Stream resource = assembly.GetManifestResourceStream("MyLibrary._fonts.OpenSans.ttf");
    

    The key point is to use the right name on GetManifestResourceStream call. You have to use [assembly name].[directory].[file name].

    Ref link: https://stackoverflow.com/a/41106851/4778712