7 out of 11 rated this helpful - Rate this topic

Code Quick Start: Create an application that stores a file in Windows Azure storage

Updated: November 30, 2011

The following steps describe how to create a console application that uses the Windows Azure Storage Services API. Specifically this sample will upload a file to the Windows Azure Blob service.

This sample does not get deployed to Windows Azure; rather, it shows you how to call the Windows Azure storage client library through a stand-alone console application.

If you do not already have a Windows Azure subscription, you can use this topic up through Step 10 to upload a file to the local Blob service running in the Windows Azure storage emulator.

  1. Launch Microsoft Visual Studio 2010.

  2. On the File menu, click New, and then click Project.

  3. Within the New Project dialog, navigate to Installed Templates, Visual C#, and click Windows.

  4. Click Console Application. Choose .NET Framework 4 from the drop down list. If needed, modify the Location: field, which indicates where your solution will be stored. For purposes of this sample, use StorageSample as the name of the project. Click OK to close the New Project dialog.

  5. From the Project menu, click Add Reference…. Within the Browse tab of the Add Reference dialog, navigate to where your Windows Azure SDK reference libraries are installed, making sure to use the latest version. By default, in Windows Azure SDK versions 1.7 and greater, the reference libraries are installed to the C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\<sdk-version>\ref directory. In versions 1.6 and earlier, they are installed to C:\Program Files\Windows Azure SDK\<sdk-version>\ref\. Select Microsoft.WindowsAzure.StorageClient.dll and click OK.

  6. From the Project menu, click StorageSample Properties. Within the Application tab of the Properties dialog, set the Target Framework to .NET Framework 4 (not .NET Framework 4 Client). Close the Properties dialog.

  7. Modify Program.cs to contain the following code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.StorageClient;
    
    namespace StorageSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    // Variables for the cloud storage objects.
                    CloudStorageAccount cloudStorageAccount;
                    CloudBlobClient blobClient;
                    CloudBlobContainer blobContainer;
                    BlobContainerPermissions containerPermissions;
                    CloudBlob blob;
    
                    // Use the emulatedstorage account.
                    cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
    
                    // If you want to use Windows Azure cloud storage account, use the following
                    // code (after uncommenting) instead of the code above.
                    // cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=your_storage_account_name;AccountKey=your_storage_account_key");
    
                    // Create the blob client, which provides
                    // authenticated access to the Blob service.
                    blobClient = cloudStorageAccount.CreateCloudBlobClient();
    
                    // Get the container reference.
                    blobContainer = blobClient.GetContainerReference("mycontainer");
                    // Create the container if it does not exist.
                    blobContainer.CreateIfNotExist();
    
                    // Set permissions on the container.
                    containerPermissions = new BlobContainerPermissions();
                    // This sample sets the container to have public blobs. Your application
                    // needs may be different. See the documentation for BlobContainerPermissions
                    // for more information about blob container permissions.
                    containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                    blobContainer.SetPermissions(containerPermissions);
    
                    // Get a reference to the blob.
                    blob = blobContainer.GetBlobReference("myfile.txt");
    
                    // Upload a file from the local system to the blob.
                    Console.WriteLine("Starting file upload");
                    blob.UploadFile(@"c:\myfiles\myfile.txt");  // File from emulated storage.
                    Console.WriteLine("File upload complete to blob " + blob.Uri);
                }
                catch (StorageClientException e)
                {
                    Console.WriteLine("Storage client error encountered: " + e.Message);
    
                    // Exit the application with exit code 1.
                    System.Environment.Exit(1);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error encountered: " + e.Message);
    
                    // Exit the application with exit code 1.
                    System.Environment.Exit(1);
                }
                finally
                {
                    // Exit the application.
                    System.Environment.Exit(0);
                }
            }
        }
    }
    
    
  8. Create a file on your local computer named c:\myfiles\myfile.txt. Alternatively, use an existing file, but change the following code to reference the existing file instead of c:\myfiles\myfile.txt:

    blob.UploadFile(@"c:\myfiles\myfile.txt");  // File from emulated storage.
    
    
  9. Save Program.cs.

  10. Since the code is using the local Blob service, start the Windows Azure storage emulator. In Windows, click the Windows Start icon, click All Programs, click Windows Azure Emulators – November 2011, and click Storage Emulator. Alternatively, if the Windows Azure Emulator icon is in your task bar, you can start the storage emulator via right-clicking the Windows Azure Emulator icon and then clicking Start Storage Emulator.

  11. On the Debug menu, click Start Without Debugging. Assuming no compile errors or client machine errors, the program should now run successfully. Copy the URI displayed by the application to your browser, and you should be able to view the file that you uploaded to the local Blob service, since you are using the emulatedstorage account. The following code was used to specify the emulated storage account:

    cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
    

    For more information about the storage emulator, see Configuring and Using the Storage Emulator with Visual Studio.

  12. Now let’s set up the code to upload the file to your Windows Azure storage account, instead of to your emulated storage account. If you haven’t already done so, create a Windows Azure storage account by following the instructions at How to Create a Storage Account for a Windows Azure Subscription.

  13. In Program.cs, comment out the following code line, since you’ll be using a Windows Azure storage account and not the storage emulator:

    // cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
    
    
  14. Modify the Program.cs code to use your storage account information. Your values are needed in this section of code, which specifies the connection string to use for Windows Azure storage:

    cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=your_storage_account_name;AccountKey=your_storage_account_key");
    
    

    Ensure this line of code is no longer commented out. Modify the values assigned to your_storage_account_name and your_storage_account_key to use your storage account name and your storage account access key, respectively. You can use the Windows Azure Management Portal, http://manage.windowsazure.com, to determine both of those values. Specifically, within http://manage.windowsazure.com, you can navigate to Hosted Services, Storage Accounts, and CDN, and then click Storage Accounts, to see the storage account name(s) listed for your subscription(s). Click a storage account to see the storage account properties page. The following shows the storage account properties page, with callouts to where you would see the storage account name and the primary access key:

    Storage account properties

    In the code above, replace the text your_storage_account_name with the name of your storage account. Replace your_storage_account_key with either the primary or secondary storage access key value. For more information about connection strings, see Configuring Connection Strings.

    securitySecurity Note
    Ensure that you maintain secrecy of your storage account keys. Secure your application and source, including Program.cs, since it now contains your storage account credentials.

  15. Save Program.cs.

  16. On the Debug menu, click Start Without Debugging. Assuming no compile errors or client machine errors, the program should now run successfully. Copy the URI displayed by the application to your browser, and you should be able to view the file that you uploaded to your Windows Azure storage account.

The sample code acquires an instance of the CloudStorageAccount class, which encapsulates the credentials needed to authenticate a request against the storage services. This object is then used to create an instance of the CloudBlobClient class, which provides access to the Blob service. Using the CloudBlobClient instance, the sample acquires a reference to a blob container named mycontainer, creating it if it does not exist. The container’s permission is set to allow anonymous access at the blob level. For information about the various types of permissions available to a container, see BlobContainerPermissions. Finally, the sample uploads a local file to the blob named myfile.txt by calling the UploadFile method. Note that the blob name need not be the same name as the local file name.

In addition to being able to view the blob using the blob URI you can view the blob within Visual Studio. For information on how to view the blob within Visual Studio, see Browsing Storage Resources with the Windows Azure Storage Explorer. Also, a variety of third-party Windows Azure storage viewing software is available and can be found by searching online.

As you would expect for a storage entity, there are many methods and properties available for blobs. For example, you can upload text to a blob through the UploadText method, or download a blob to a file through the DownloadToFile method. If you want to delete the blob that you uploaded, call the Delete method. For more information about blob methods and properties, see CloudBlob.

Similarly, there are many methods and properties for containers. For example, you can enumerate the blobs in a container by using the ListBlobs method, or delete a container through the Delete method. For more information about container methods and properties, see CloudBlobContainer.

Other types of clients besides CloudBlobClient that can be acquired through an instance of the CloudStorageAccount class are CloudTableClient and CloudQueueClient, which are for used for operations on Windows Azure tables and queues, respectively. For more information about the .NET managed library for Windows Azure Storage Services, see Microsoft.WindowsAzure.StorageClient.

In addition to the .NET managed library provided by the Windows Azure Storage Services API, a REST API is also provided for storage functionality. For more information, see Windows Azure Storage Services REST API Reference.

See Also

Did you find this helpful?
(1500 characters remaining)

Community Additions

© 2013 Microsoft. All rights reserved.
facebook page visit twitter rss feed newsletter