2

我正在尝试将 Windows Azure 存储用于我的带有移动服务的 Windows Store 应用程序来存储图像。我按照本指南进行了上传工作:

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

但是,我找不到任何有关下载文件的材料。我什至找不到 Windows 商店版本的类参考!如果有人可以指导我查看文档,我将不胜感激。

无论如何,我编写了代码,但它似乎不起作用:

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);
        }
    }
}

此代码会导致创建空文件,但它不会引发任何异常。如果我将 imageUri 的值粘贴到我的浏览器,它会开始下载文件并成功完成下载。但是,由于某种原因,我的程序没有。

请问有什么帮助吗?

4

1 回答 1

2

显然,我一直以错误的方式打开流。这是一个修复:

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);
        }
    }
}

它现在完美运行。

于 2013-04-06T11:25:47.353 回答