Search code examples
asp.net-coreazure-functionsazure-storageazure-blob-storageazure-table-storage

how to send file to the azure storage from azure function app


I am using a azure function app(service bus) which triggers everytime when a excel file get uploaded in the UI. And for any reason if the excel file was not able to upload then it throws exception message. I want to store that exception message into the text file and store that text file into the storage account. Plz suggest me how to store that file that into the stotage account from my function app.

The exception code goes like this:

catch (Exception ex)
        {
            logger.LogInformation($"Exception: {ex.Message}, {ex.StackTrace}");
            return "Failure";
        }

Solution

  • Maybe you can try to use this code:

                catch (Exception ex)
                {
                    log.LogInformation($"Exception: {ex.Message}, {ex.StackTrace}");
    
                    string connectionString = "";
                    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
                    string containerName = "";
    
                    // Create a local file in the ./data/ directory for uploading and downloading
                    string localPath = "./data/";
                    string fileName = "exception" + Guid.NewGuid().ToString() + ".txt";
                    string localFilePath = Path.Combine(localPath, fileName);
    
                    // Write text to the file
                    await File.WriteAllTextAsync(localFilePath, $"Exception: {ex.Message}, {ex.StackTrace}");
                    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
                    // Get a reference to a blob
                    BlobClient blobClient = containerClient.GetBlobClient(fileName);
    
                    // Open the file and upload its data
                    using FileStream uploadFileStream = File.OpenRead(localFilePath);
                    await blobClient.UploadAsync(uploadFileStream, true);
                    uploadFileStream.Close();
    
                    return "Failure";
                }
    

    Please refer to this official documentation.