How to get data directly from request.form.file[0] instead of copying it to server ?

ahmed salah 3,216 Reputation points
2021-09-10T13:13:08.973+00:00

I work on c# 7 I face issue I can't get data from file Request.form.file[0] directly

it must copying to server to get data from it
so can i get data from variable DisplayFileName

instead of get data from input path after copying to server
below is my code :

 //step1 get file from angular
         var DisplayFileName = Request.Form.Files[0];
         //step2 modify file name to be unique to avoid make error if exist before 
         string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + DateTime.Now.Ticks.ToString() + ".xlsx";
         // step3 make unique input path with input data  but not create yet
         string inputpath = Path.Combine(myValue1, DateTime.Now.Month.ToString(), fileName);
         // step4 make unique output path will export final result to it  but not create yet
         string exportPath = Path.Combine(myValue2, DateTime.Now.Month.ToString(), fileName);
         CExcel ex = new CExcel();
         //step5 check input file have data
         if (fileName.Length > 0)
         {
           //step6 create file with input data i uploaded on server path on Input folder
             using (var stream = new FileStream(inputpath, FileMode.Create))
             {
                 Request.Form.Files[0].CopyTo(stream);

             }

with another meaning How to get data direct from
DisplayFileName
I don't need get data from inputpath variable
that i create on server

for more details how to get data direct from step1
instead of get data from step 6 after copying data to server ?
How to get data direct from step 1 please ?

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | ASP.NET API
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

1 answer

Sort by: Most helpful
  1. P a u l 10,761 Reputation points
    2021-09-10T17:16:49.783+00:00

    Here's how I would get the file data:

    public async Task<IActionResult> Upload() {
        IFormFile file = Request.Form.Files[0];
    
        using (Stream stream = file.OpenReadStream())
        using (StreamReader reader = new StreamReader(stream)) {
            string data = await reader.ReadToEndAsync();
    
            // Do something with file data
        }
    
        return View();
    }
    

    You can get a Stream from the IFormFile, then open a StreamReader on it and read all the data with the ReadToEndAsync call.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.