Ace
Ace

Reputation: 938

reading content of blob from azure function

I'm trying to read the content of a blob inside an azure function.

Here's the code:

Note: If I comment out the using block and return the blob i.e.

return new OkObjectResult(blob);

I get back the blob object.

However, if I use the using block, I get 500.

Any idea why I can't get the content?

string storageConnectionString = "myConnectionString";
CloudStorageAccount storageAccount;
CloudStorageAccount.TryParse(storageConnectionString, out storageAccount);
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = cloudBlobClient.GetContainerReference("drawcontainer");


var blob = drawingsContainer.GetBlockBlobReference("notes.txt");

using (StreamReader reader = new StreamReader(blob.OpenRead()))
{
    content = reader.ReadToEnd();
}
return new OkObjectResult(content);

Upvotes: 0

Views: 417

Answers (2)

Ace
Ace

Reputation: 938

The OpenRead method didn't exist so I used the async one and it solved it.

I got to this solution after creating an azure function in VS and publishing it and it works.

Here's the code I used:

 public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<ActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
    {
        log.Info("C# HTTP trigger function processed a request.");
        string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=avitest19a1c;AccountKey=<AccessKey>";
        CloudStorageAccount storageAccount = null;
        CloudStorageAccount.TryParse(storageConnectionString, out storageAccount);
        CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer drawingsContainer = cloudBlobClient.GetContainerReference("drawcontainer");

        var blob = drawingsContainer.GetBlockBlobReference("notes.txt");

        string content = string.Empty;
        **var contentStream = await blob.OpenReadAsync();**
        using (StreamReader reader = new StreamReader(contentStream))
        {
            content = reader.ReadToEnd();
        }

        return new OkObjectResult(content);

    }
}

Upvotes: 1

Anish K
Anish K

Reputation: 818

HTTP 500 indicates that the code has error. The most probable reason for error is the variable 'content'. Define the variable 'content' outside the using block as the scope of the content variable defined inside it is limited to the block only. Declare it outside the using block, something like below:

    try
    {
        string content = string.Empty;
        using (StreamReader reader = new StreamReader(blob.OpenRead()))
        {
            content = reader.ReadToEnd();
        }
    }
    catch (Exception ex)
    {
        // Log exception to get the details.    
    }

Always make use of try catch to get more details about errors in the code.

Upvotes: 1

Related Questions