2
votes

I'm trying to use Windows Azure Storage for my Windows Store App with Mobile Services to store images. I made uploading work by following this guide:

http://www.windowsazure.com/en-us/develop/mobile/tutorials/upload-images-to-storage-dotnet/

However, I couldn't find any material on downloading the files. I couldn't even find classes reference for windows store version! If someone could guide me to the documentation I would be grateful.

Anyway, I wrote the code but it doesn't seem work:

public static async System.Threading.Tasks.Task DownloadUserImage(SQLUser userData)
{
    var usersFolder = await GetUsersFolder();
    var imageUri = new Uri(userData.ImageUri);
    var accountName = "<SNIP>";
    var key = "<SNIP>";

    StorageCredentials cred = new StorageCredentials(accountName, key);
    CloudBlobContainer container = new CloudBlobContainer(new Uri(string.Format("https://{0}/{1}", imageUri.Host, userData.ContainerName)), cred);
    CloudBlockBlob blob = container.GetBlockBlobReference(userData.ResourceName);

    var imageFile = await usersFolder.CreateFileAsync(userData.Id.ToString() + ".jpg", CreationCollisionOption.ReplaceExisting);
    using (var fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
    {
        try
        {
            await blob.DownloadToStreamAsync(fileStream);
        }
        catch (Exception e)
        {
            Tools.HandleLiveException(e);
        }
    }
}

This code results in empty file creation, but it doesn't throw any exceptions whatsoever. If I paste the value of imageUri to my browser, it starts downloading the file and completes the download successfully. However, my program does not, for some reason.

Any help, please?

1

1 Answers

2
votes

Apparently, I've been opening the stream in a wrong way. Here's a fix:

public static async System.Threading.Tasks.Task DownloadUserImage(SQLUser userData)
{
    var usersFolder = await GetUsersFolder();
    var imageUri = new Uri(userData.ImageUri);
    var accountName = "<SNIP>";
    var key = "<SNIP>";

    StorageCredentials cred = new StorageCredentials(accountName, key);
    CloudBlobClient client = new CloudBlobClient(new Uri(string.Format("https://{0}", imageUri.Host)), cred);
    CloudBlobContainer container = client.GetContainerReference(userData.ContainerName);
    var blob = await container.GetBlobReferenceFromServerAsync(userData.ResourceName);

    var imageFile = await usersFolder.CreateFileAsync(userData.Id.ToString() + ".jpg", CreationCollisionOption.ReplaceExisting);
    using (var fileStream = await imageFile.OpenStreamForWriteAsync())
    {
        try
        {
            await blob.DownloadToStreamAsync(fileStream.AsOutputStream());
        }
        catch (Exception e)
        {
            Tools.HandleLiveException(e);
        }
    }
}

It works perfectly now.