简体   繁体   中英

File upload/Download IOException: The process cannot access the file '' because it is being used by another process .net core

I'm trying to implement file upload/ download the upload is successful but when i try to download the file i get the error message
IOException: The process cannot access the file '' because it is being used by another process

Upload Code

   public async Task<IActionResult> Create(AttachmentViewModel attachment, IFormFile[] Files)
    {

        LawyerAPI lawyerAPI = new LawyerAPI();
        HttpClient httpClient = lawyerAPI.InitializeClient();
        ViewBag.TypeName = attachment.Type;
        ViewBag.TypeID = attachment.TypeID;
        if (Files != null && Files.Count() > 0)
        {
            attachment.attachmentFiles = new List<AttachmentFilesViewModel>();
            var dir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploaded_Files/" + attachment.Type + "/" + attachment.TypeID);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            foreach (var item in Files)
            {
                AttachmentFilesViewModel att = new AttachmentFilesViewModel();


                att.FileExt = Path.GetExtension(item.FileName);
                att.FileName = item.FileName;
                // att.files = item;
                attachment.attachmentFiles.Add(att);


                var path = Path.Combine(dir, item.FileName);
                var stream = new FileStream(path, FileMode.Create);
                await item.CopyToAsync(stream);

            }
            HttpResponseMessage res = await httpClient.PostAsJsonAsync("api/nofactory/createattachment", attachment);
            if (res.IsSuccessStatusCode)
            {
                return Json("Success");
            }
        }

       
        return Json("Failed");
         
    }
 

download

   public async Task<IActionResult> DownloadFile(string filename)
    {
         var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploaded_Files/", filename);
        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        return File(memory, GetContentType(path), Path.GetFileName(path));
       // return View(attachList);
    }
    private string GetContentType(string path)
    {
        var types = GetMimeTypes();
        var ext = Path.GetExtension(path).ToLowerInvariant();
        return types[ext];
    }

    private Dictionary<string, string> GetMimeTypes()
    {
        return new Dictionary<string, string>
        {
            {".txt", "text/plain"},
            {".pdf", "application/pdf"},
            {".doc", "application/vnd.ms-word"},
            {".docx", "application/vnd.ms-word"},
            {".xls", "application/vnd.ms-excel"},
            {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {".png", "image/png"},
            {".jpg", "image/jpeg"},
            {".jpeg", "image/jpeg"},
            {".gif", "image/gif"},
            {".csv", "text/csv"}
        };
    }

i tried to open the file using windows explorer i get the same message when i close the debugger i can open the file i almost sure the the visual studio is the process blocking the file why? and how to fix? thanks

.net core 2.2

Instead of reading the file into a MemoryStream i would return the file stream directly like this:

using var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return File(stream, GetContentType(path), Path.GetFileName(path))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM