Quickstart: Face client library for .NET

Get started with the Face client library for .NET. Follow these steps to install the package and try out the example code for basic tasks. The Face service provides you with access to advanced algorithms for detecting and recognizing human faces in images.

Use the Face client library for .NET to:

Reference documentation | Library source code | Package (NuGet) | Samples

Prerequisites

Setting up

Create a Face Azure resource

Azure Cognitive Services are represented by Azure resources that you subscribe to. Create a resource for Face using the Azure portal or Azure CLI on your local machine. You can also:

After you get a key from your trial subscription or resource, create an environment variable for the key and endpoint URL, named FACE_SUBSCRIPTION_KEY and FACE_ENDPOINT, respectively.

Create a new C# application

Create a new .NET Core application in your preferred editor or IDE.

In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name face-quickstart. This command creates a simple "Hello World" C# project with a single source file: Program.cs.

dotnet new console -n face-quickstart

Change your directory to the newly created app folder. You can build the application with:

dotnet build

The build output should contain no warnings or errors.

...
Build succeeded.
 0 Warning(s)
 0 Error(s)
...

From the project directory, open the Program.cs file in your preferred editor or IDE. Add the following using directives:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Azure.CognitiveServices.Vision.Face;
using Microsoft.Azure.CognitiveServices.Vision.Face.Models;

In the application's Main method, create variables for your resource's Azure endpoint and key.

// From your Face subscription in the Azure portal, get your subscription key and endpoint.
// Set your environment variables using the names below. Close and reopen your project for changes to take effect.
string SUBSCRIPTION_KEY = Environment.GetEnvironmentVariable("FACE_SUBSCRIPTION_KEY");
string ENDPOINT = Environment.GetEnvironmentVariable("FACE_ENDPOINT");

Install the client library

Within the application directory, install the Face client library for .NET with the following command:

dotnet add package Microsoft.Azure.CognitiveServices.Vision.Face --version 2.5.0-preview.1

If you're using the Visual Studio IDE, the client library is available as a downloadable NuGet package.

Object model

The following classes and interfaces handle some of the major features of the Face .NET SDK:

Name Description
FaceClient This class represents your authorization to use the Face service, and you need it for all Face functionality. You instantiate it with your subscription information, and you use it to produce instances of other classes.
FaceOperations This class handles the basic detection and recognition tasks that you can do with human faces.
DetectedFace This class represents all of the data that was detected from a single face in an image. You can use it to retrieve detailed information about the face.
FaceListOperations This class manages the cloud-stored FaceList constructs, which store an assorted set of faces.
PersonGroupPersonExtensions This class manages the cloud-stored Person constructs, which store a set of faces that belong to a single person.
PersonGroupOperations This class manages the cloud-stored PersonGroup constructs, which store a set of assorted Person objects.
ShapshotOperations This class manages the Snapshot functionality. You can use it to temporarily save all of your cloud-based Face data and migrate that data to a new Azure subscription.

Code examples

The code snippets below show you how to do the following tasks with the Face client library for .NET:

Authenticate the client

Note

This quickstart assumes you've created environment variables for your Face key and endpoint, named FACE_SUBSCRIPTION_KEY and FACE_ENDPOINT.

In a new method, instantiate a client with your endpoint and key. Create a CognitiveServicesCredentials object with your key, and use it with your endpoint to create a FaceClient object.

/*
 *	AUTHENTICATE
 *	Uses subscription key and region to create a client.
 */
public static IFaceClient Authenticate(string endpoint, string key)
{
    return new FaceClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint };
}

You'll likely want to call this method in the Main method.

// Authenticate.
IFaceClient client = Authenticate(ENDPOINT, SUBSCRIPTION_KEY);

Detect faces in an image

At the root of your class, define the following URL string. This URL points to a set of sample images.

// Used for all examples.
// URL for the images.
const string IMAGE_BASE_URL = "https://csdx.blob.core.windows.net/resources/Face/Images/";

Optionally, you can choose which AI model to use to extract data from the detected face(s). See Specify a recognition model for information on these options.

// Used in the Detect Faces and Verify examples.
// Recognition model 2 is used for feature extraction, use 1 to simply recognize/detect a face. 
// However, the API calls to Detection that are used with Verify, Find Similar, or Identify must share the same recognition model.
const string RECOGNITION_MODEL2 = RecognitionModel.Recognition02;
const string RECOGNITION_MODEL1 = RecognitionModel.Recognition01;

The final Detect operation will take a FaceClient object, an image URL, and a recognition model.

// Detect - get features from faces.
DetectFaceExtract(client, IMAGE_BASE_URL, RECOGNITION_MODEL2).Wait();

Get detected face objects

In the next block of code, the DetectFaceExtract method detects faces in three of the images at the given URL and creates a list of DetectedFace objects in program memory. The list of FaceAttributeType values specifies which features to extract.

/* 
 * DETECT FACES
 * Detects features from faces and IDs them.
 */
public static async Task DetectFaceExtract(IFaceClient client, string url, string recognitionModel)
{
    Console.WriteLine("========DETECT FACES========");
    Console.WriteLine();

    // Create a list of images
    List<string> imageFileNames = new List<string>
                    {
                        "detection1.jpg",    // single female with glasses
                        // "detection2.jpg", // (optional: single man)
                        // "detection3.jpg", // (optional: single male construction worker)
                        // "detection4.jpg", // (optional: 3 people at cafe, 1 is blurred)
                        "detection5.jpg",    // family, woman child man
                        "detection6.jpg"     // elderly couple, male female
                    };

    foreach (var imageFileName in imageFileNames)
    {
        IList<DetectedFace> detectedFaces;

        // Detect faces with all attributes from image url.
        detectedFaces = await client.Face.DetectWithUrlAsync($"{url}{imageFileName}",
                returnFaceAttributes: new List<FaceAttributeType> { FaceAttributeType.Accessories, FaceAttributeType.Age,
                FaceAttributeType.Blur, FaceAttributeType.Emotion, FaceAttributeType.Exposure, FaceAttributeType.FacialHair,
                FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Hair, FaceAttributeType.HeadPose,
                FaceAttributeType.Makeup, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.Smile },
                recognitionModel: recognitionModel);

        Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{imageFileName}`.");

Display detected face data

The rest of the DetectFaceExtract method parses and prints the attribute data for each detected face. Each attribute must be specified separately in the original face detection API call (in the FaceAttributeType list). The following code processes every attribute, but you will likely only need to use one or a few.

        // Parse and print all attributes of each detected face.
        foreach (var face in detectedFaces)
        {
            Console.WriteLine($"Face attributes for {imageFileName}:");

            // Get bounding box of the faces
            Console.WriteLine($"Rectangle(Left/Top/Width/Height) : {face.FaceRectangle.Left} {face.FaceRectangle.Top} {face.FaceRectangle.Width} {face.FaceRectangle.Height}");

            // Get accessories of the faces
            List<Accessory> accessoriesList = (List<Accessory>)face.FaceAttributes.Accessories;
            int count = face.FaceAttributes.Accessories.Count;
            string accessory; string[] accessoryArray = new string[count];
            if (count == 0) { accessory = "NoAccessories"; }
            else
            {
                for (int i = 0; i < count; ++i) { accessoryArray[i] = accessoriesList[i].Type.ToString(); }
                accessory = string.Join(",", accessoryArray);
            }
            Console.WriteLine($"Accessories : {accessory}");

            // Get face other attributes
            Console.WriteLine($"Age : {face.FaceAttributes.Age}");
            Console.WriteLine($"Blur : {face.FaceAttributes.Blur.BlurLevel}");

            // Get emotion on the face
            string emotionType = string.Empty;
            double emotionValue = 0.0;
            Emotion emotion = face.FaceAttributes.Emotion;
            if (emotion.Anger > emotionValue) { emotionValue = emotion.Anger; emotionType = "Anger"; }
            if (emotion.Contempt > emotionValue) { emotionValue = emotion.Contempt; emotionType = "Contempt"; }
            if (emotion.Disgust > emotionValue) { emotionValue = emotion.Disgust; emotionType = "Disgust"; }
            if (emotion.Fear > emotionValue) { emotionValue = emotion.Fear; emotionType = "Fear"; }
            if (emotion.Happiness > emotionValue) { emotionValue = emotion.Happiness; emotionType = "Happiness"; }
            if (emotion.Neutral > emotionValue) { emotionValue = emotion.Neutral; emotionType = "Neutral"; }
            if (emotion.Sadness > emotionValue) { emotionValue = emotion.Sadness; emotionType = "Sadness"; }
            if (emotion.Surprise > emotionValue) { emotionType = "Surprise"; }
            Console.WriteLine($"Emotion : {emotionType}");

            // Get more face attributes
            Console.WriteLine($"Exposure : {face.FaceAttributes.Exposure.ExposureLevel}");
            Console.WriteLine($"FacialHair : {string.Format("{0}", face.FaceAttributes.FacialHair.Moustache + face.FaceAttributes.FacialHair.Beard + face.FaceAttributes.FacialHair.Sideburns > 0 ? "Yes" : "No")}");
            Console.WriteLine($"Gender : {face.FaceAttributes.Gender}");
            Console.WriteLine($"Glasses : {face.FaceAttributes.Glasses}");

            // Get hair color
            Hair hair = face.FaceAttributes.Hair;
            string color = null;
            if (hair.HairColor.Count == 0) { if (hair.Invisible) { color = "Invisible"; } else { color = "Bald"; } }
            HairColorType returnColor = HairColorType.Unknown;
            double maxConfidence = 0.0f;
            foreach (HairColor hairColor in hair.HairColor)
            {
                if (hairColor.Confidence <= maxConfidence) { continue; }
                maxConfidence = hairColor.Confidence; returnColor = hairColor.Color; color = returnColor.ToString();
            }
            Console.WriteLine($"Hair : {color}");

            // Get more attributes
            Console.WriteLine($"HeadPose : {string.Format("Pitch: {0}, Roll: {1}, Yaw: {2}", Math.Round(face.FaceAttributes.HeadPose.Pitch, 2), Math.Round(face.FaceAttributes.HeadPose.Roll, 2), Math.Round(face.FaceAttributes.HeadPose.Yaw, 2))}");
            Console.WriteLine($"Makeup : {string.Format("{0}", (face.FaceAttributes.Makeup.EyeMakeup || face.FaceAttributes.Makeup.LipMakeup) ? "Yes" : "No")}");
            Console.WriteLine($"Noise : {face.FaceAttributes.Noise.NoiseLevel}");
            Console.WriteLine($"Occlusion : {string.Format("EyeOccluded: {0}", face.FaceAttributes.Occlusion.EyeOccluded ? "Yes" : "No")} " +
                $" {string.Format("ForeheadOccluded: {0}", face.FaceAttributes.Occlusion.ForeheadOccluded ? "Yes" : "No")}   {string.Format("MouthOccluded: {0}", face.FaceAttributes.Occlusion.MouthOccluded ? "Yes" : "No")}");
            Console.WriteLine($"Smile : {face.FaceAttributes.Smile}");
            Console.WriteLine();
        }
    }
}

Find similar faces

The following code takes a single detected face (source) and searches a set of other faces (target) to find matches. When it finds a match, it prints the ID of the matched face to the console.

Detect faces for comparison

First, define a second face detection method. You need to detect faces in images before you can compare them, and this detection method is optimized for comparison operations. It doesn't extract detailed face attributes like in the section above, and it uses a different recognition model.

private static async Task<List<DetectedFace>> DetectFaceRecognize(IFaceClient faceClient, string url, string RECOGNITION_MODEL1)
{
    // Detect faces from image URL. Since only recognizing, use the recognition model 1.
    IList<DetectedFace> detectedFaces = await faceClient.Face.DetectWithUrlAsync(url, recognitionModel: RECOGNITION_MODEL1);
    Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{Path.GetFileName(url)}`");
    return detectedFaces.ToList();
}

Find matches

The following method detects faces in a set of target images and in a single source image. Then, it compares them and finds all the target images that are similar to the source image.

/*
 * FIND SIMILAR
 * This example will take an image and find a similar one to it in another image.
 */
public static async Task FindSimilar(IFaceClient client, string url, string RECOGNITION_MODEL1)
{
    Console.WriteLine("========FIND SIMILAR========");
    Console.WriteLine();

    List<string> targetImageFileNames = new List<string>
                        {
                            "Family1-Dad1.jpg",
                            "Family1-Daughter1.jpg",
                            "Family1-Mom1.jpg",
                            "Family1-Son1.jpg",
                            "Family2-Lady1.jpg",
                            "Family2-Man1.jpg",
                            "Family3-Lady1.jpg",
                            "Family3-Man1.jpg"
                        };

    string sourceImageFileName = "findsimilar.jpg";
    IList<Guid?> targetFaceIds = new List<Guid?>();
    foreach (var targetImageFileName in targetImageFileNames)
    {
        // Detect faces from target image url.
        var faces = await DetectFaceRecognize(client, $"{url}{targetImageFileName}", RECOGNITION_MODEL1);
        // Add detected faceId to list of GUIDs.
        targetFaceIds.Add(faces[0].FaceId.Value);
    }

    // Detect faces from source image url.
    IList<DetectedFace> detectedFaces = await DetectFaceRecognize(client, $"{url}{sourceImageFileName}", RECOGNITION_MODEL1);
    Console.WriteLine();

    // Find a similar face(s) in the list of IDs. Comapring only the first in list for testing purposes.
    IList<SimilarFace> similarResults = await client.Face.FindSimilarAsync(detectedFaces[0].FaceId.Value, null, null, targetFaceIds);

The following code prints the match details to the console:

foreach (var similarResult in similarResults)
{
    Console.WriteLine($"Faces from {sourceImageFileName} & ID:{similarResult.FaceId} are similar with confidence: {similarResult.Confidence}.");
}
Console.WriteLine();

Create and train a person group

The following code creates a PersonGroup with six different Person objects. It associates each Person with a set of example images, and then it trains to recognize each person by their facial characteristics. Person and PersonGroup objects are used in the Verify, Identify, and Group operations.

If you haven't done so already, define the following URL string at the root of your class. This points to a set of sample images.

// Used for all examples.
// URL for the images.
const string IMAGE_BASE_URL = "https://csdx.blob.core.windows.net/resources/Face/Images/";

The code later in this section will specify a recognition model to extract data from faces, and the following snippet creates references to the available models. See Specify a recognition model for information on recognition models.

// Used in the Detect Faces and Verify examples.
// Recognition model 2 is used for feature extraction, use 1 to simply recognize/detect a face. 
// However, the API calls to Detection that are used with Verify, Find Similar, or Identify must share the same recognition model.
const string RECOGNITION_MODEL2 = RecognitionModel.Recognition02;
const string RECOGNITION_MODEL1 = RecognitionModel.Recognition01;

Create PersonGroup

Declare a string variable at the root of your class to represent the ID of the PersonGroup you'll create.

static string sourcePersonGroup = null;

In a new method, add the following code. This code associates the names of persons with their example images.

// Create a dictionary for all your images, grouping similar ones under the same key.
Dictionary<string, string[]> personDictionary =
    new Dictionary<string, string[]>
        { { "Family1-Dad", new[] { "Family1-Dad1.jpg", "Family1-Dad2.jpg" } },
          { "Family1-Mom", new[] { "Family1-Mom1.jpg", "Family1-Mom2.jpg" } },
          { "Family1-Son", new[] { "Family1-Son1.jpg", "Family1-Son2.jpg" } },
          { "Family1-Daughter", new[] { "Family1-Daughter1.jpg", "Family1-Daughter2.jpg" } },
          { "Family2-Lady", new[] { "Family2-Lady1.jpg", "Family2-Lady2.jpg" } },
          { "Family2-Man", new[] { "Family2-Man1.jpg", "Family2-Man2.jpg" } }
        };
// A group photo that includes some of the persons you seek to identify from your dictionary.
string sourceImageFileName = "identification1.jpg";

Next, add the following code to create a Person object for each person in the Dictionary and add the face data from the appropriate images. Each Person object is associated with the same PersonGroup through its unique ID string. Remember to pass the variables client, url, and RECOGNITION_MODEL1 into this method.

// Create a person group. 
string personGroupId = Guid.NewGuid().ToString();
sourcePersonGroup = personGroupId; // This is solely for the snapshot operations example
Console.WriteLine($"Create a person group ({personGroupId}).");
await client.PersonGroup.CreateAsync(personGroupId, personGroupId, recognitionModel: recognitionModel);
// The similar faces will be grouped into a single person group person.
foreach (var groupedFace in personDictionary.Keys)
{
    // Limit TPS
    await Task.Delay(250);
    Person person = await client.PersonGroupPerson.CreateAsync(personGroupId: personGroupId, name: groupedFace);
    Console.WriteLine($"Create a person group person '{groupedFace}'.");

    // Add face to the person group person.
    foreach (var similarImage in personDictionary[groupedFace])
    {
        Console.WriteLine($"Add face to the person group person({groupedFace}) from image `{similarImage}`");
        PersistedFace face = await client.PersonGroupPerson.AddFaceFromUrlAsync(personGroupId, person.PersonId,
            $"{url}{similarImage}", similarImage);
    }
}

Train PersonGroup

Once you've extracted face data from your images and sorted it into different Person objects, you must train the PersonGroup to identify the visual features associated with each of its Person objects. The following code calls the asynchronous train method and polls the results, printing the status to the console.

// Start to train the person group.
Console.WriteLine();
Console.WriteLine($"Train person group {personGroupId}.");
await client.PersonGroup.TrainAsync(personGroupId);

// Wait until the training is completed.
while (true)
{
    await Task.Delay(1000);
    var trainingStatus = await client.PersonGroup.GetTrainingStatusAsync(personGroupId);
    Console.WriteLine($"Training status: {trainingStatus.Status}.");
    if (trainingStatus.Status == TrainingStatusType.Succeeded) { break; }
}

This Person group and its associated Person objects are now ready to be used in the Verify, Identify, or Group operations.

Identify a face

The Identify operation takes an image of a person (or multiple people) and looks to find the identity of each face in the image. It compares each detected face to a PersonGroup, a database of different Person objects whose facial features are known.

Important

In order to run this example, you must first run the code in Create and train a person group. The variables used in that section—client, url, and RECOGNITION_MODEL1—must also be available here.

Get a test image

Notice that the code for Create and train a person group defines a variable sourceImageFileName. This variable corresponds to the source image—the image that contains people to identify.

Identify faces

The following code takes the source image and creates a list of all the faces detected in the image. These are the faces that will be identified against the PersonGroup.

List<Guid> sourceFaceIds = new List<Guid>();
// Detect faces from source image url.
List<DetectedFace> detectedFaces = await DetectFaceRecognize(client, $"{url}{sourceImageFileName}", recognitionModel);

// Add detected faceId to sourceFaceIds.
foreach (var detectedFace in detectedFaces) { sourceFaceIds.Add(detectedFace.FaceId.Value); }

The next code snippet calls the Identify operation and prints the results to the console. Here, the service attempts to match each face from the source image to a Person in the given PersonGroup.

// Identify the faces in a person group. 
var identifyResults = await client.Face.IdentifyAsync(sourceFaceIds, personGroupId);

foreach (var identifyResult in identifyResults)
{
    Person person = await client.PersonGroupPerson.GetAsync(personGroupId, identifyResult.Candidates[0].PersonId);
    Console.WriteLine($"Person '{person.Name}' is identified for face in: {sourceImageFileName} - {identifyResult.FaceId}," +
        $" confidence: {identifyResult.Candidates[0].Confidence}.");
}
Console.WriteLine();

Take a snapshot for data migration

The Snapshots feature lets you move your saved Face data, such as a trained PersonGroup, to a different Azure Cognitive Services Face subscription. You may want to use this feature if, for example, you've created a PersonGroup object using a free trial subscription and want to migrate it to a paid subscription. See Migrate your face data for an overview of the Snapshots feature.

In this example, you will migrate the PersonGroup you created in Create and train a person group. You can either complete that section first, or create your own Face data construct(s) to migrate.

Set up target subscription

First, you must have a second Azure subscription with a Face resource; you can do this by following the steps in the Setting up section.

Then, define the following variables in the Main method of your program. You'll need to create new environment variables for the subscription ID of your Azure account, as well as the key, endpoint, and subscription ID of your new (target) account.

// The Snapshot example needs its own 2nd client, since it uses two different regions.
string TARGET_SUBSCRIPTION_KEY = Environment.GetEnvironmentVariable("FACE_SUBSCRIPTION_KEY2");
string TARGET_ENDPOINT = Environment.GetEnvironmentVariable("FACE_ENDPOINT2");
// Grab your subscription ID, from any resource in Azure, from the Overview page (all resources have the same subscription ID). 
Guid AZURE_SUBSCRIPTION_ID = new Guid(Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID"));
// Target subscription ID. It will be the same as the source ID if created Face resources from the same
// subscription (but moving from region to region). If they are different subscriptions, add the other
// target ID here.
Guid TARGET_AZURE_SUBSCRIPTION_ID = new Guid(Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID"));

For this example, declare a variable for the ID of the target PersonGroup—the object that belongs to the new subscription, which you will copy your data to.

// The Snapshot example needs its own 2nd client, since it uses two different regions.
string TARGET_SUBSCRIPTION_KEY = Environment.GetEnvironmentVariable("FACE_SUBSCRIPTION_KEY2");
string TARGET_ENDPOINT = Environment.GetEnvironmentVariable("FACE_ENDPOINT2");
// Grab your subscription ID, from any resource in Azure, from the Overview page (all resources have the same subscription ID). 
Guid AZURE_SUBSCRIPTION_ID = new Guid(Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID"));
// Target subscription ID. It will be the same as the source ID if created Face resources from the same
// subscription (but moving from region to region). If they are different subscriptions, add the other
// target ID here.
Guid TARGET_AZURE_SUBSCRIPTION_ID = new Guid(Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID"));

Authenticate target client

Next, add the code to authenticate your secondary Face subscription.

// Authenticate for another region or subscription (used in Snapshot only).
IFaceClient clientTarget = Authenticate(TARGET_ENDPOINT, TARGET_SUBSCRIPTION_KEY);

Use a snapshot

The rest of the snapshot operations must take place within an asynchronous method.

  1. The first step is to take the snapshot, which saves your original subscription's face data to a temporary cloud location. This method returns an ID that you use to query the status of the operation.

    /*
     * SNAPSHOT OPERATIONS
     * Copies a person group from one Azure region (or subscription) to another. For example: from the EastUS region to the WestUS.
     * The same process can be used for face lists. 
     * NOTE: the person group in the target region has a new person group ID, so it no longer associates with the source person group.
     */
    public static async Task Snapshot(IFaceClient clientSource, IFaceClient clientTarget, string personGroupId, Guid azureId, Guid targetAzureId)
    {
        Console.WriteLine("========SNAPSHOT OPERATIONS========");
        Console.WriteLine();
    
        // Take a snapshot for the person group that was previously created in your source region.
        var takeSnapshotResult = await clientSource.Snapshot.TakeAsync(SnapshotObjectType.PersonGroup, personGroupId, new[] { azureId }); // add targetAzureId to this array if your target ID is different from your source ID.
        
        // Get operation id from response for tracking the progress of snapshot taking.
        var operationId = Guid.Parse(takeSnapshotResult.OperationLocation.Split('/')[2]);
        Console.WriteLine($"Taking snapshot(operation ID: {operationId})... Started");
    
  2. Next, query the ID until the operation has completed.

    // Wait for taking the snapshot to complete.
    OperationStatus operationStatus = null;
    do
    {
        Thread.Sleep(TimeSpan.FromMilliseconds(1000));
        // Get the status of the operation.
        operationStatus = await clientSource.Snapshot.GetOperationStatusAsync(operationId);
        Console.WriteLine($"Operation Status: {operationStatus.Status}");
    }
    while (operationStatus.Status != OperationStatusType.Succeeded && operationStatus.Status != OperationStatusType.Failed);
    // Confirm the location of the resource where the snapshot is taken and its snapshot ID
    var snapshotId = Guid.Parse(operationStatus.ResourceLocation.Split('/')[2]);
    Console.WriteLine($"Source region snapshot ID: {snapshotId}");
    Console.WriteLine($"Taking snapshot of person group: {personGroupId}... Done\n");
    
  3. Then use the apply operation to write your face data to your target subscription. This method also returns an ID value.

    // Apply the snapshot in target region, with a new ID.
    var newPersonGroupId = Guid.NewGuid().ToString();
    targetPersonGroup = newPersonGroupId;
    
    try
    {
        var applySnapshotResult = await clientTarget.Snapshot.ApplyAsync(snapshotId, newPersonGroupId);
    
        // Get operation id from response for tracking the progress of snapshot applying.
        var applyOperationId = Guid.Parse(applySnapshotResult.OperationLocation.Split('/')[2]);
        Console.WriteLine($"Applying snapshot(operation ID: {applyOperationId})... Started");
    
  4. Again, query the new ID until the operation has completed.

    // Apply the snapshot in target region, with a new ID.
    var newPersonGroupId = Guid.NewGuid().ToString();
    targetPersonGroup = newPersonGroupId;
    
    try
    {
        var applySnapshotResult = await clientTarget.Snapshot.ApplyAsync(snapshotId, newPersonGroupId);
    
        // Get operation id from response for tracking the progress of snapshot applying.
        var applyOperationId = Guid.Parse(applySnapshotResult.OperationLocation.Split('/')[2]);
        Console.WriteLine($"Applying snapshot(operation ID: {applyOperationId})... Started");
    
  5. Finally, complete the try/catch block and finish the method.

        catch (Exception e)
        {
            throw new ApplicationException("Do you have a second Face resource in Azure? " +
                "It's needed to transfer the person group to it for the Snapshot example.", e);
        }
    }
    

At this point, your new PersonGroup object should have the same data as the original one and should be accessible from your new (target) Azure Face subscription.

Run the application

Run the application from your application directory with the dotnet run command.

dotnet run

Clean up resources

If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

If you created a PersonGroup in this quickstart and you want to delete it, run the following code in your program:

// At end, delete person groups in both regions (since testing only)
Console.WriteLine("========DELETE PERSON GROUP========");
Console.WriteLine();
DeletePersonGroup(client, sourcePersonGroup).Wait();

Define the deletion method with the following code:

/*
 * DELETE PERSON GROUP
 * After this entire example is executed, delete the person group in your Azure account,
 * otherwise you cannot recreate one with the same name (if running example repeatedly).
 */
public static async Task DeletePersonGroup(IFaceClient client, String personGroupId)
{
    await client.PersonGroup.DeleteAsync(personGroupId);
    Console.WriteLine($"Deleted the person group {personGroupId}.");
}

Additionally, if you migrated data using the Snapshot feature in this quickstart, you'll also need to delete the PersonGroup saved to the target subscription.

DeletePersonGroup(clientTarget, targetPersonGroup).Wait();
Console.WriteLine();

Next steps

In this quickstart, you learned how to use the Face library for .NET to do basis tasks. Next, explore the reference documentation to learn more about the library.