I am trying to implement a file upload component in my Blazor web application. I am using the approach provided on the Core Blazor InputFile
component documentation page.
Here is my code:
await using FileStream fs = new(path, FileMode.Create);
await file.OpenReadStream(MaxFileSize).CopyToAsync(fs);
If OpenReadStream
throws an error, (MaxFileSize
is exceeded, etc.) the file should not be uploaded. However, since I already created the file stream, an empty file is created at the provided path (an empty text document for example). I am a C# and Blazor newbie so I'm probably just overlooking an easy solution. How can I ensure that an empty file is not uploaded even if an error is thrown?
CodePudding user response:
Well, you can create the file after you've called OpenReadStream
:
using var input = file.OpenReadStream(MaxFileSize);
await using FileStream output = new(path, FileMode.Create);
await input.CopyTo(output);
That could still fail leaving an empty or incomplete file of course, because CopyTo
could fail, but it at least avoids the problem when OpenReadStream
throws an exception.
CodePudding user response:
I believe it will be enough to add a file delete action in the catch block.
So your example would look like following:
try
{
await using FileStream fs = new(path, FileMode.Create);
await file.OpenReadStream(MaxFileSize).CopyToAsync(fs);
}
catch (Exception ex)
{
File.Delete(path);
//Re-throw exception
throw;
}
CodePudding user response:
If it's actually throwing an error. Break up the statements and surround with a try catch?
try
{
var strm = await file.OpenReadStream(MaxFileSize);
strm.CopyToAsync(fs);
}
catch
{
}
Or check the stream for content before copying in an if statement.