Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request.Content.ReadAsMultipartAsync Throws System.IO exception

I am uploading an image to an ASP WebAPI service and then uploading it to windows azure. everything was working great but suddenly I started getting the following exception:

        System.IO.IOException: The process cannot access the file
        'C:\DWASFiles\Sites\Tasteat\Temp\BodyPart_a5c79910-6077-4c24-b814-10fdc0e0b3d4' 
        because it is being used by another process.

This is the code that throws the exception:

    var provider = new BlobStorageProvider(container);
    Trace.TraceInformation("Uploading raw image to blob");
    await Request.Content.ReadAsMultipartAsync(provider);
    Trace.TraceInformation("Uploading finished");

I know its this line await Request.Content.ReadAsMultipartAsync(provider); because I see the line before it in the log but not the line after it.

Any ideas?

Everything was working great up until a few days

like image 734
Amit Raz Avatar asked Nov 01 '22 18:11

Amit Raz


1 Answers

So as it seems the code I posted above actually saves a local file and only then uploaded it to the server, which causes the error but also is slow. after a lot of trying I finally change to the following solution and everything started working and it was even faster!

first create a streamprovider:

public class BlobStorageMultipartStreamProvider : MultipartStreamProvider
    {
        private readonly string _containerName;
        private readonly string _fileName;

        public BlobStorageMultipartStreamProvider(string containerName, string fileName)
        {
            _containerName = containerName;
            _fileName = fileName;
        }

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            Stream stream = null;

            if (!String.IsNullOrWhiteSpace(_fileName))
                {
                    string connectionString = ConfigurationManager.ConnectionStrings["BlobStorage"].ConnectionString;
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer blobContainer = blobClient.GetContainerReference(_containerName);
                    CloudBlockBlob blob = blobContainer.GetBlockBlobReference(_fileName);
                    stream = blob.OpenWrite();
                }
            return stream;
        }
    }

The upload code:

 string fileName = Guid.NewGuid()+".Png";
                MultipartStreamProvider provider = new BlobStorageMultipartStreamProvider("container",fileName);
                Trace.TraceInformation("Uploading raw image to blob");                
                await Request.Content.ReadAsMultipartAsync(provider);
                Trace.TraceInformation("Uploading finished");
like image 141
Amit Raz Avatar answered Nov 15 '22 05:11

Amit Raz