I have an API Upload Controller, which has a parameter IFormFile. From Swagger, I am passing a.zip file which has a few.json files inside. I want to get these.json files from that.zip that I receive from Swagger and pass them to a service that will process them.
So I managed to create a logic like this. I save the.zip file in (~Temp>settings) directory, the next thing I want to do is unzip that file and send the.json files into a different directory named "temp-json-imports". So then I can get the.json files and work with them.
Here is the code that I have written so far, this doesn't work, it fails on the last line - (ZipFile.ExtractToDirectory(filePath, tmpJsonImports);), with an exception of type System.IO.IOException (like shown in the picture below). Any ideas on how can I solve this problem would be very much welcome. :)
[HttpPost("import/{applicationId}")]
public async Task<IActionResult> ImportSettings([FromRoute] Guid applicationId, IFormFile file)
{
string tempPath = Path.Combine(_hostingEnvironment.ContentRootPath, Path.GetTempPath());
string tmpSettingsPath = Path.Combine(tempPath, "settings");
string tmpImportSettings = Path.Combine(tmpSettingsPath, "import");
string tmpJsonImports = Path.Combine(tmpImportSettings, "temp-json-imports");
Directory.CreateDirectory(tmpSettingsPath);
Directory.CreateDirectory(tmpImportSettings);
Directory.CreateDirectory(tmpJsonImports);
long size = file.Length;
if (size > 0)
{
var filePath = tmpImportSettings + "\\" + file.FileName;
using var stream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(stream);
string zipPath = Path.GetFileName(filePath);
ZipFile.ExtractToDirectory(filePath, tmpJsonImports);
}
return Ok();
}
Try to use your code on my application, it will show this exception:
This exception relates the following code, you didn't close the file handle after copy the file to the path.
var filePath = tmpImportSettings + "\\" + file.FileName;
using var stream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(stream);
To solve this exception, try to modify your code as below:
if (size > 0)
{
var filePath = tmpImportSettings + "\\" + fileviewmodel.File.FileName;
using (var stream = new FileStream(filePath, FileMode.Create))
{
await fileviewmodel.File.CopyToAsync(stream);
};
string zipPath = Path.GetFileName(filePath);
ZipFile.ExtractToDirectory(filePath, tmpJsonImports);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.