Search code examples
c#model-view-controllermemorystream

C# - Problem reading File memorystream in my MVC project


As my code is shown below, the uploaded image file is sometimes read empty (fileContents is set to 0) or half read. As I have tested I could see that fileContents is receiving the proper value when I slowly step-over from myViewModel.File.CopyToAsync(memoryStream); to myViewModel.Image =... using the debug mode. So I believe there is a problem with the memorystream copy but I don't understand why.

However when I sleep the thread by removing the commented System.Threading.Thread.Sleep(1000); then reading the image is done propely and the fileContents get the proper value. Can the problem be caused by the declaration using (var memoryStream = new MemoryStream())? What is the problem caused by and is there a better way to fix this issue rather than sleeping the thread?

  if (myViewModel.File != null)
        {
            byte[] fileContents;
            using (var memoryStream = new MemoryStream())
            {
                myViewModel.File.CopyToAsync(memoryStream);
                //System.Threading.Thread.Sleep(1000);
                fileContents = memoryStream.ToArray();
                myViewModel.Image = new MyImage{ FileName = myViewModel.File.FileName, File = myViewModel.File, ContentType = myViewModel.File.ContentType, FileData = fileContents };
            }
        }

Solution

  • You are not waiting for myViewModel.File.CopyToAsync(memoryStream) to complete.

    Either use

    await myViewModel.File.CopyToAsync(memoryStream);
    

    or don't use async at all:

    myViewModel.File.CopyTo(memoryStream);