Caleb Rotich
Caleb Rotich

Reputation: 653

Read a file immediately after uploading it in ASP.NET core MVC

I just uploaded a file to the wwwroot/files folder of my project. What I intend to do is read the file immediately after uploading it. The code I have used to upload the file works fine but the one for reading the file throws this Exception: An unhandled exception occurred while processing the request. IOException: The process cannot access the file 'campuses.sql' because it is being used by another process. Campuses.sql is the file I'm trying to upload and read. Below is my code for uploading and reading the file.

 public IActionResult Institution(IFormFile InstitutionFile)
    {
        if(InstitutionFile != null)
        {
            var fileName = Path.Combine(he.WebRootPath + "/files/", Path.GetFileName(InstitutionFile.FileName));
            InstitutionFile.CopyTo(new FileStream(fileName, FileMode.Create));

       //Everything runs fine till here

            int counter = 0;
            string line;

            // Read the file and display it line by line.  
            System.IO.StreamReader file =
                new System.IO.StreamReader(fileName);
            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine(line);
                counter++;
            }

            file.Close();

            System.Console.ReadLine();



        }

        return RedirectToAction("Index", "Institutions");

    }

So: 1. I suspect it is the upload process which is still using the file. How can I stop the process using the file so that I can read it?

  1. Is there another way that can help me go round this?

I intend to read data from an .csv file and insert the records into a database in the long run.

Thanks!

Upvotes: 0

Views: 2559

Answers (1)

tchelidze
tchelidze

Reputation: 8318

Read from InstitutionFile instead of physical file.

Also put FileStream into using block so it will release the file.

var fileName = Path.Combine("" + "/files/", Path.GetFileName(InstitutionFile.FileName));
using (var fileStream = new FileStream(fileName, FileMode.Create))
      InstitutionFile.CopyTo(fileStream);

var st = new MemoryStream();
InstitutionFile.CopyTo(st);
var content = Encoding.ASCII.GetString(st.ToArray());

Upvotes: 1

Related Questions