Search code examples
c#asp.net-corefilestream

System.IO.FileNotFoundException : Could not find file


I am using file upload control. But when I try to read uploaded file, it's looking for folder where project is created and giving error. The code for this

 <input type="file" name="file" />
 <button type="submit">Upload File</button>

and

[HttpPost]
    public IActionResult UploadFile(IFormFile file)
    {
        string FileName = file.FileName;
        if (file != null && file.Length != 0)
        {
            FileStream fileStream = new FileStream(FileName, FileMode.Open);
            using (StreamReader streamReader = new StreamReader(fileStream))
            {
                string line = streamReader.ReadLine();
            }

        }
    }

Solution

  • If you are trying to read the uploaded file using stream, you can use the following,

            string result;
            if (file != null && file.Length != 0)
            {
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                   result = reader.ReadToEnd();  
                }
            }
    

    Or, if you are trying to save the uploaded file somewhere in the server then you should use the CopyTo method like below example,

            var destinationPath= Path.GetTempFileName(); //Change this line to point to your actual destination
            using (var stream = new FileStream(destinationPath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }