locked
Unable to retrieve Blob Metadata even though Metadata has been saved for the Blob. Please help. RRS feed

  • Question

  • I am trying to read Metadata for the Blob that has been saved with Metadata, but the metadata collection shows none of the keys. I can see the metadata when I see it in Azure Storage Explorer. I have attached my code and Please help me. I appreciate any help.

            public CloudBlobContainer GetBlobContainerRef(string containerName)
            {
                CloudBlobContainer cloudBlobContainer = null;
                try
                {
                    CloudStorageAccount cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                    CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

                    cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);
                    cloudBlobContainer.CreateIfNotExist();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                return cloudBlobContainer;
            }
            public string GetBlobUri(CloudBlobContainer _BlobContainer, string blobName)
            {
                string blobUri = string.Empty;
                try
                {
                    IEnumerable<IListBlobItem> blobList = _BlobContainer.ListBlobs();

                    //find whether the blob file exists
                    foreach (var blobItem in blobList)
                    {
                        string uri = blobItem.Uri.ToString();
                        if (uri.Contains(blobName))
                        {
                            blobUri = uri;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Failed to get Blob Uri: \n {0}", ex.ToString());
                }
                finally { }

                return blobUri;
            }

            private string SaveFileToBlob(string filePath)
            {
                int uploadBlockSize = 1048576;
                CloudBlockBlob blob;
                CloudBlobContainer cloudBlobContainer = null;
                string blobUri = string.Empty;

                string[] strArray = filePath.Split(new char[1] { '\\' });
                FileInfo file = new FileInfo(strArray[strArray.Length - 1]);

                string blobName = file.Name;
                try
                {
                    cloudBlobContainer = blobService.GetBlobContainerRef(ContainerName);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError("Unable to get Blob Container reference.\n{0}", ex.ToString());
                    return string.Empty;
                }

                blob = cloudBlobContainer.GetBlockBlobReference(blobName);
                FileStream fileStream = null;
                try
                {
                    fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read);
                    long totalFileSize = fileStream.Length;
                    // Progressively read the file stream. Read [blockSize] bytes each time.
                    int bytesRead = 0;
                    int totalBytesRead = 0;
                    int i = 0;
                    byte[] buffer = new byte[uploadBlockSize];
                    // Keep a list of block IDs.
                    List<string> blockIDList = new List<string>();
                    // Read the first block.
                    bytesRead = fileStream.Read(buffer, 0, uploadBlockSize);

                    while (bytesRead > 0)
                    {
                        using (MemoryStream ms = new MemoryStream(buffer, 0, bytesRead))
                        {
                            char[] tempID = new char[6];
                            string iStr = i.ToString();
                            for (int j = tempID.Length - 1; j > tempID.Length - iStr.Length - 1; j--)
                            {
                                tempID[j] = iStr[tempID.Length - j - 1];
                            }
                            byte[] blockIDBeforeEncoding = Encoding.UTF8.GetBytes(tempID);
                            string blockID = Convert.ToBase64String(blockIDBeforeEncoding);
                            blockIDList.Add(blockID);

                            blob.PutBlock(blockID, ms, null);
                        }
                        totalBytesRead += bytesRead;
                        i++;

                        bytesRead = fileStream.Read(buffer, 0, uploadBlockSize);

                    }
                    blob.PutBlockList(blockIDList);
                    blob.Metadata["FileName"] = file.Name;
                    blob.Metadata["CreatedDate"] = DateTime.Now.ToString();
                    blob.SetMetadata();

                    GetBlobMetadata();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError("Unable to save the file to Blob.\n {0}", ex.ToString());
                    blobName = string.Empty;
                }
                finally
                {
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                }

                return blobName;
            }

      private void GetBlobMetadata()
            {
                CloudBlobContainer cloudBlobContainer = null;
                string blobUri = string.Empty;
                BlobService blobService = null;
                try
                {
                    blobService = new BlobService();
                    cloudBlobContainer = blobService.GetBlobContainerRef(ContainerName);
                    string blobName = BlobName;
                    blobUri = blobService.GetBlobUri(cloudBlobContainer, blobName);
                    var blob = cloudBlobContainer.GetBlobReference(blobUri);
        blob.FetchAttributes();
                    int i = 0;
                    foreach (string key in blob.Metadata.Keys)
                    {
                        System.Diagnostics.Trace.TraceInformation("KeyName: {0}", key);
                        string[] values = blob.Metadata.GetValues(i);
                        foreach (string val in values)
                            System.Diagnostics.Trace.TraceInformation("KeyValue: {0}", val);
                        i++;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.TraceError("Unable to get metadata for blob [{0}].\n{1}", BlobName, ex.ToString());
                    return;
                }
            }

     

    Thanks,

    Ravi

    Wednesday, June 8, 2011 6:43 PM

Answers

  • Hi Ravi,

    The code looks fine. Could you please add a break point to your code to check if blob.Metadata has value or not before running the foreach loop? As you have wrapped the statements with a try-catch statement, could you please check if there is an exception thrown or not?

    Besides, I provide a sample code that successfully retrieve and display the metadata from a blob.

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
    CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
    CloudBlob blob = blobStorage.GetBlobReference("files/myfile.zip");
    blob.FetchAttributes();
    foreach (string key in blob.Metadata.Keys)
    {
        string value = blob.Metadata.Get(key);
        Console.WriteLine("{0}: {1}", key, value);
    }

    Thanks,


    Wengchao Zeng
    Please mark the replies as answers if they help or unmark if not.
    If you have any feedback about my replies, please contact msdnmg@microsoft.com.
    Microsoft One Code Framework
    • Marked as answer by Wenchao Zeng Friday, June 10, 2011 3:17 AM
    Thursday, June 9, 2011 6:44 AM

All replies

  • Hi Ravi,

    The code looks fine. Could you please add a break point to your code to check if blob.Metadata has value or not before running the foreach loop? As you have wrapped the statements with a try-catch statement, could you please check if there is an exception thrown or not?

    Besides, I provide a sample code that successfully retrieve and display the metadata from a blob.

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
    CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
    CloudBlob blob = blobStorage.GetBlobReference("files/myfile.zip");
    blob.FetchAttributes();
    foreach (string key in blob.Metadata.Keys)
    {
        string value = blob.Metadata.Get(key);
        Console.WriteLine("{0}: {1}", key, value);
    }

    Thanks,


    Wengchao Zeng
    Please mark the replies as answers if they help or unmark if not.
    If you have any feedback about my replies, please contact msdnmg@microsoft.com.
    Microsoft One Code Framework
    • Marked as answer by Wenchao Zeng Friday, June 10, 2011 3:17 AM
    Thursday, June 9, 2011 6:44 AM
  • It is working now.

    Thanks,

    Ravi

    Thursday, June 9, 2011 5:03 PM
  • Thanks Wenchao. So it turns out one has to call  blob. FetchAttributes() to make the metadata ready. I think that's the key.
    Friday, April 27, 2012 3:18 PM