Search code examples
.net-coreblazor.net-5

Track writen data instead of read data in a file stream


I'm trying to follow this guide for making a progressbar with blazor server-side

https://www.meziantou.net/file-upload-with-progress-bar-in-blazor.htm

I then want to write the files to the file system, the problem is that reading it is much faster than actually writing it to the disk meaning it seems stuck at 100% for quite some time at large files.

So can i make it track how much it have written to the disk instead. or maybe them synchronized.

await using FileStream fs = new(path, FileMode.Create);
using var stream = file.OpenReadStream(maxFileSize);
while (await stream.ReadAsync(buffer) is int read && read > 0)
{
    //Writing to disk
    await fs.WriteAsync(buffer.AsMemory(0, read));
    //Updating how much data has been read
    uploadedFiles[startIndex].UploadedBytes += read;        
}

EDIT: After trying the answer it made more sense, and because i'm using an azure file share. There is some delay for that. Checking the filesize directly on the file would give me the right progress but way to slow.

Think i will store the file locally, before transfering to the fileShare. Or looking into blobStorage transfer.


Solution

  • Reading and Writing are already happening interleaved.

    The only thing that could possibly help here is to Flush:

    while (await stream.ReadAsync(buffer) is int read && read > 0)
    {
        //Writing to disk
        await fs.WriteAsync(buffer.AsMemory(0, read));
        // Force the actual writing
        await fs.FlushAsync();
        //Updating how much data has been read
        uploadedFiles[startIndex].UploadedBytes += read;    
    }
    

    Without this the FileSystem is free to keep the data in a buffer until you Close the file.

    Do note that repeatedly Flushing will probably increase the total time for the upload.