I am trying to upload files to Azure blob storage in .Net Core 2.1. Below is my code.
IFormFileCollection files = formCollection.Files;
foreach (var file in files)
{
if (file.Length > 0)
{
_azureCloudStorage.UploadContent(cloudBlobContainer, file.OpenReadStream(), file.FileName);
}
}
UploadContent
implementation-
public async void UploadContent(CloudBlobContainer containerReference, Stream contentStream, string blobName)
{
try
{
using (contentStream)
{
var blockBlobRef = containerReference.GetBlockBlobReference(blobName);
//await containerReference.SetPermissionsAsync(new BlobContainerPermissions
//{
// PublicAccess = BlobContainerPublicAccessType.Blob
//});
await blockBlobRef.UploadFromStreamAsync(contentStream);
}
}
catch(Exception ex)
{
//Error here
}
}
The code executes with below error-
{System.ObjectDisposedException: Cannot access a closed file. at System.IO.FileStream.get_Position() at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.get_Position() at Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.VerifyPosition() at Microsoft.AspNetCore.Http.Internal.ReferenceReadStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) at Microsoft.WindowsAzure.Storage.Core.Util.StreamExtensions.WriteToAsync[T](Stream stream, Stream toStream, IBufferManager bufferManager, Nullable
1 copyLength, Nullable
1 maxLength, Boolean calculateMd5, ExecutionState1 executionState, StreamDescriptor streamCopyState, CancellationToken token) in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Core\Util\StreamExtensions.cs:line 301 at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStreamAsyncHelper(Stream source, Nullable
1 length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, IProgress1 progressHandler, CancellationToken cancellationToken) in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Blob\CloudBlockBlob.cs:line 352 at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStreamAsyncHelper(Stream source, Nullable
1 length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Blob\CloudBlockBlob.cs:line 290 at Common.AzureCloudStorage.UploadContent(CloudBlobContainer containerReference, Stream contentStream, String blobName)
Alternate solution which worked for me: adding to azure blob storage with stream
Any help with this please? Please let me know if I can provide more details.