I have this code that should upload all Attachment sent by user:
private async Task<List<AttchmentsMetaData>> UploadAttachments(IEnumerable<IFormFile> Attachments, string TaskTitle)
{
// 1. Configure storage location and path generation
string uploadPath = Path.Combine(_hostingEnvironment.ContentRootPath, "attachments",$"{TaskTitle}" );
List<AttchmentsMetaData> metaData = [];
// 2. Process and store each uploaded file
Directory.CreateDirectory(uploadPath);
foreach (IFormFile attach in Attachments)
{
string uniqueFileName = attach.FileName;
string fullPath = Path.Combine(uploadPath, uniqueFileName);
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
await attach.CopyToAsync(stream);
}
metaData.Add( new AttchmentsMetaData {id = Guid.NewGuid().ToString(), OriginalFileName = attach.FileName, ContentType = attach.ContentType, FileSize = attach.Length });
}
return (metaData);
}
If Attachment has only one item it works, but if has more than one it fails in the second iteration giving the above error:
System.ObjectDisposedException: 'Cannot access a disposed object. Object name: 'System.String'.'
I tried to add manual dispose for the file stream.
I tried to call the function multiple times and passing just one item.
Edited :
This is more info The thread 0x3838 has exited with code 0 (0x0). Exception thrown: 'System.ObjectDisposedException' in System.Private.CoreLib.dll Exception thrown: 'System.ObjectDisposedException' in System.Private.CoreLib.dll An exception of type 'System.ObjectDisposedException' occurred in System.Private.CoreLib.dll but was not handled in user code Cannot access a disposed object.
Object name: 'System.String'. at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.set_Position(Int64 value) at Microsoft.AspNetCore.Http.FormFile.OpenReadStream() at Microsoft.AspNetCore.Http.FormFile.CopyToAsync(Stream target, CancellationToken cancellationToken) at ticketing_system_Dev_Nxt_level.Services.TaskService.UploadAttachments(IEnumerable`1 Attachments, String TaskTitle) in D:\ASP.NET\ticketing-system-Dev-Nxt-level\Services\TaskService.cs:line 334
Ok one of my colleagues solved it for me by changing the code inside the using block