Wednesday, 21 August 2024

File upload to blob using C#

 public async Task<bool> CapitalItemFileUploadtoCloud(IFormFileCollection _lstFiles, string _strIncidentId)

        {
            var blobServiceClient = new BlobServiceClient(strAzureConnectionString);
            try
            {
                bool _blnResult = false;
                var blobContainerClient = blobServiceClient.GetBlobContainerClient(strEnvironment); // Container reference

 

                // Create the container if it doesn't exist
                await blobContainerClient.CreateIfNotExistsAsync();

 

                foreach (var file in _lstFiles)
                {
                    if (file.Length > 0)
                    {
                        // Create a reference to the blob within the container
                        var blobClient = blobContainerClient.GetBlobClient($"{_strIncidentId}/{file.FileName}");

 

                        // Upload the file to the blob
                        using (var stream = new MemoryStream())
                        {
                            try
                            {
                                stream.Seek(0, SeekOrigin.Begin);
                                await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = file.ContentType });
                                _blnResult = true; // Set result to true if upload succeeds
                            }
                            catch (Exception uploadEx)
                            {
                                // Handle exceptions during upload
                                Console.WriteLine($"Upload failed: {uploadEx.Message}");
                                _blnResult = false;
                            }
                        }
                    }
                }

 

                return _blnResult;
            }
            catch (Exception ex)
            {
                // Handle exceptions during setup or container operations
                Console.WriteLine($"An error occurred: {ex.Message}");
                return false;
            }
        }

No comments:

Post a Comment

7 Common mistakes in Dot Net — You can avoid

  There are many common mistakes made during .NET (ASP.NET, .NET Core) development, which affect performance, security, and code… Code Crack...