Quickstart: Using C# to call the Text Analytics Cognitive Service

This article shows you how to detect language, analyze sentiment, and extract key phrases by using the Text Analytics APIs with C#. The code was written to work on a .NET Core application, with minimal references to external libraries, so you can also run it on Linux or MacOS.

Refer to the API definitions for technical documentation for the APIs.

The source code for this sample is available on GitHub.


You must have a Cognitive Services API account with the Text Analytics API. You can use the free tier for 5,000 transactions/month to complete this quickstart.

You must also have the endpoint and access key that were generated for you during sign-up.

Install the NuGet SDK package

  1. Create a new console solution in Visual Studio.
  2. Right-click the solution and select Manage NuGet Packages for Solution.
  3. Select the Include Prerelease check box.
  4. Select the Browse tab, and search for Microsoft.Azure.CognitiveServices.Language.
  5. Select the Microsoft.Azure.CognitiveServices.Language.TextAnalytics NuGet package and install it.


Although you can call the HTTP endpoints directly from C#, the Microsoft.Azure.CognitiveServices.Language SDK makes it much easier to call the service without having to worry about serializing and deserializing JSON.

Here are useful links:

Call the Text Analytics API by using the SDK

  1. Replace Program.cs with the following code. This program demonstrates the capabilities of the Text Analytics API in three sections (language extraction, key-phrase extraction, and sentiment analysis).
  2. Replace the Ocp-Apim-Subscription-Key header value with an access key that's valid for your subscription.
  3. Replace the location in Endpoint to the endpoint that you signed up for. You can find the endpoint on the Azure portal resource. The endpoint typically starts with "https://[region].api.cognitive.microsoft.com." Include only the protocol and host name.
  4. Run the program.
using System;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics.Models;
using System.Collections.Generic;
using Microsoft.Rest;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
    class Program
        /// <summary>
        /// Container for subscription credentials. Make sure to enter your valid key.
        /// </summary>
        class ApiKeyServiceClientCredentials : ServiceClientCredentials
            public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
                request.Headers.Add("Ocp-Apim-Subscription-Key", "ENTER KEY HERE");
                return base.ProcessHttpRequestAsync(request, cancellationToken);

        static void Main(string[] args)

            // Create a client.
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
                Endpoint = "https://westus.api.cognitive.microsoft.com"

            Console.OutputEncoding = System.Text.Encoding.UTF8;

Detect language

The Language Detection API detects the language of a text document, using the Detect Language method.

            // Extracting language.
            Console.WriteLine("===== LANGUAGE EXTRACTION ======");

            var result =  client.DetectLanguageAsync(new BatchInput(
                    new List<Input>()
                          new Input("1", "This is a document written in English."),
                          new Input("2", "Este es un document escrito en Español."),
                          new Input("3", "这是一个用中文写的文件")

            // Printing language results.
            foreach (var document in result.Documents)
                Console.WriteLine("Document ID: {0} , Language: {1}", document.Id, document.DetectedLanguages[0].Name);

Extract key phrases

The Key Phrase Extraction API extracts key-phrases from a text document, using the Key Phrases method.

            // Getting key phrases.
            Console.WriteLine("\n\n===== KEY-PHRASE EXTRACTION ======");

            KeyPhraseBatchResult result2 = client.KeyPhrasesAsync(new MultiLanguageBatchInput(
                        new List<MultiLanguageInput>()
                          new MultiLanguageInput("ja", "1", "猫は幸せ"),
                          new MultiLanguageInput("de", "2", "Fahrt nach Stuttgart und dann zum Hotel zu Fu."),
                          new MultiLanguageInput("en", "3", "My cat is stiff as a rock."),
                          new MultiLanguageInput("es", "4", "A mi me encanta el fútbol!")

            // Printing key phrases.
            foreach (var document in result2.Documents)
                Console.WriteLine("Document ID: {0} ", document.Id);

                Console.WriteLine("\t Key phrases:");

                foreach (string keyphrase in document.KeyPhrases)
                    Console.WriteLine("\t\t" + keyphrase);

Analyze sentiment

The Sentiment Analysis API detects the sentiment of a set of text records, using the Sentiment method.

            // Analyzing sentiment.
            Console.WriteLine("\n\n===== SENTIMENT ANALYSIS ======");

            SentimentBatchResult result3 = client.SentimentAsync(
                    new MultiLanguageBatchInput(
                        new List<MultiLanguageInput>()
                          new MultiLanguageInput("en", "0", "I had the best day of my life."),
                          new MultiLanguageInput("en", "1", "This was a waste of my time. The speaker put me to sleep."),
                          new MultiLanguageInput("es", "2", "No tengo dinero ni nada que dar..."),
                          new MultiLanguageInput("it", "3", "L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."),

            // Printing sentiment results.
            foreach (var document in result3.Documents)
                Console.WriteLine("Document ID: {0} , Sentiment Score: {1:0.00}", document.Id, document.Score);

Identify linked entities

The Entity Linking API identifies well-known entities in a text document, using the Entity Linking method.

            // Linking entities
            Console.WriteLine("\n\n===== ENTITY LINKING ======");

            EntitiesBatchResult result4 = client.EntitiesAsync(
                    new MultiLanguageBatchInput(
                        new List<MultiLanguageInput>()
                            new MultiLanguageInput("en", "0", "I really enjoy the new XBox One S. It has a clean look, it has 4K/HDR resolution and it is affordable."),
                            new MultiLanguageInput("en", "1", "The Seattle Seahawks won the Super Bowl in 2014."),

            // Printing entity results.
            foreach (var document in result4.Documents)
                Console.WriteLine("Document ID: {0} , Entities: {1}", document.Id, String.Join(", ", document.Entities.Select(entity => entity.Name)));

Next steps

See also

Text Analytics overview
Frequently asked questions (FAQ)