User guide

Table Of Contents
foreach (KeyPairInfo item in myKeyPairs)
{
Console.WriteLine("Existing key pair: " + item.KeyName);
if (item.KeyName == keyPairName)
{
myKeyPair = item;
}
}
Creating a Key Pair and Saving the Private Key
The example in this section follows from the example in the previous section. If the key pair doesn't already
exist, create it. Be sure to save the private key now, because you can't retrieve it later.
To create a key pair and save the private key
Create and initialize a CreateKeyPairRequest object. Set the KeyName property to the name of the key
pair.
Pass the request object to the CreateKeyPair method, which returns a CreateKeyPairResponse object.
The response object includes a CreateKeyPairResult property that contains the new key's KeyPair object.
The KeyPair object's KeyMaterial property contains the unencrypted private key for the key pair. Save
the private key as a .pem file in a safe location.You'll need this file when you connect to your instance.
This example saves the private key in the current directory, using the name of the key pair as the base
file name of the .pem file.
if (myKeyPair == null)
{
var newKeyRequest = new CreateKeyPairRequest()
{
KeyName = keyPairName
};
var ckpResponse = ec2Client.CreateKeyPair(newKeyRequest);
Console.WriteLine();
Console.WriteLine("New key: " + keyPairName);
// Save the private key in a .pem file
using (FileStream s = new FileStream(keyPairName + ".pem", FileMode.Create))
using (StreamWriter writer = new StreamWriter(s))
{
writer.WriteLine(ckpResponse.KeyPair.KeyMaterial);
}
}
Launch an EC2 Instance Using the SDK for .NET
Use the following procedure to launch one or more identically configured EC2 instances from the same
Amazon Machine Image (AMI). After you create your EC2 instances, you can check their status. After
your EC2 instances are running, you can connect to them.
Contents
Launching an EC2 Instance (p. 42)
Version v2.0.0
41
AWS SDK for .NET Developer Guide
Launch an EC2 Instance