Azure.RequestFailedException: The request body is too large and exceeds the maximum permissible limit.

Summary

If you are uploading a file to Azure Fileshare that is over 4MB, you will get an error message:

Azure.RequestFailedException: The request body is too large and exceeds the maximum permissible limit.

This usually happens when your code resembles the following:

            ShareClient share = new(connectionString, fileShareName);
            {
                var directory = share.GetDirectoryClient(folderName);
                var file = directory.GetFileClient(fileName);

                using FileStream stream = File.OpenRead(localFilePath);

                file.Create(stream.Length);
                file.UploadRange(new HttpRange(0, stream.Length), stream);
            }

The trick is to use chunking to avoid the 4MB limit.

The limitations of Azure Storage are documented here: https://docs.microsoft.com/en-us/azure/storage/common/scalability-targets-standard-account

The updated code:

 ShareClient share = new(connectionString, fileShareName);
            {
                var directory = share.GetDirectoryClient(folderName);
                var file = directory.GetFileClient(fileName);

                using FileStream stream = File.OpenRead(localFilePath);

                file.Create(stream.Length);
           

                int blockSize = 1 * 1024;
                long offset = 0;//Define http range offset
                BinaryReader reader = new BinaryReader(stream);
                while (true)
                {
                    byte[] buffer = reader.ReadBytes(blockSize);
                    if (buffer.Length == 0)
                        break;

                    MemoryStream uploadChunk = new MemoryStream();
                    uploadChunk.Write(buffer, 0, buffer.Length);
                    uploadChunk.Position = 0;

                    HttpRange httpRange = new HttpRange(offset, buffer.Length);
                    var resp = file.UploadRange(httpRange, uploadChunk);
                    offset += buffer.Length;//Shift the offset by number of bytes already written
                }

                reader.Close();
            }

You must be logged in to post a comment.