How can I read a file which will be upload from a form in .Net Core API?
In you Controller :
- Check if
IFormFile file
contains something - Check if the file's extension is the one you are looking for (.dat)
- Check if the file's Mime type is correct to avoid attacks
Then, if it is all right, call a Service class to read your file.
In your Service, you can do something like that :
var result = new StringBuilder();
using (var reader = new StreamReader(file.OpenReadStream()))
{
while (reader.Peek() >= 0)
result.AppendLine(await reader.ReadLineAsync());
}
return result.ToString();
Hope it helps.
The file will be bound to your IFormFile
param. You can access the stream via:
using (var stream = file.OpenReadStream())
{
// do something with stream
}
If you want to read it as a string, you'll need an instance of StreamReader
:
string fileContents;
using (var stream = file.OpenReadStream())
using (var reader = new StreamReader(stream))
{
fileContents = await reader.ReadToEndAsync();
}