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

This article shows you how to detect language, analyze sentiment, and extract key phrases 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 could also run it on Linux or MacOS.

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


You must have a Cognitive Services API subscription with access to the Text Analytics API. If you don't have a subscription, you can create an account for free. Before continuing, you will need the Text Analytics subscription key provided after activating your account.

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

Install the NuGet SDK Package

  1. Create a new Console solution in Visual Studio.
  2. Right click on the solution and click Manage NuGet Packages for Solution
  3. Mark the Include Prerelease checkbox.
  4. Select the Browse tab, and Search for Microsoft.Azure.CognitiveServices.Language.TextAnalytics
  5. Select the NuGet package and install it.


While you could 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.

A few useful links:

Call the Text Analytics API using the SDK

  1. Replace Program.cs with the code provided below. 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 valid for your subscription.
  3. Replace the location in Endpoint to the endpoint you signed up for. You can find the endpoint on Azure portal resource. The endpoint typically starts with "https://[region].api.cognitive.microsoft.com", and in here only include protocol and hostname.
  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.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.
        private const string SubscriptionKey = ""; //Insert your Text Anaytics subscription key

        /// </summary>
        class ApiKeyServiceClientCredentials : ServiceClientCredentials
            public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
                request.Headers.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);
                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"
            }; //Replace 'westus' with the correct region for your Text Analytics subscription

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

            // 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: {document.Id} , Language: {document.DetectedLanguages[0].Name}");

            // 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 keyphrases
            foreach (var document in result2.Documents)
                Console.WriteLine($"Document ID: {document.Id} ");

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

                foreach (string keyphrase in document.KeyPhrases)

            // Extracting 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: {document.Id} , Sentiment Score: {document.Score:0.00}");

            // Identify entities
            Console.WriteLine("\n\n===== ENTITIES ======");

            EntitiesBatchResultV2dot1 result4 = client.EntitiesAsync(
                    new MultiLanguageBatchInput(
                        new List<MultiLanguageInput>()
                          new MultiLanguageInput("en", "0", "The Great Depression began in 1929. By 1933, the GDP in America fell by 25%.")

            // Printing entities results
            foreach (var document in result4.Documents)
                Console.WriteLine($"Document ID: {document.Id} ");

                Console.WriteLine("\t Entities:");

                foreach (EntityRecordV2dot1 entity in document.Entities)


Application output

The application displays the following information:

Document ID: 1 , Language: English
Document ID: 2 , Language: Spanish
Document ID: 3 , Language: Chinese_Simplified

Document ID: 1
         Key phrases:
Document ID: 2
         Key phrases:
Document ID: 3
         Key phrases:
Document ID: 4
         Key phrases:

Document ID: 0 , Sentiment Score: 0.87
Document ID: 1 , Sentiment Score: 0.11
Document ID: 2 , Sentiment Score: 0.44
Document ID: 3 , Sentiment Score: 1.00

Next steps

See also

Text Analytics overview Frequently asked questions (FAQ)