The abstraction for IFormFile has a .OpenReadStream method. To prevent a ton of unwanted and potentially large selections, we must read one line at a time and make our list of each line that we read. In addition, we could wrap this logic in an extension method. Index action looks something like this:
public List<string> Index(IFormFile file) => file.ReadAsList();
The appropriate extension method is as follows:
public static List<string> ReadAsList(this IFormFile file) { var result = new StringBuilder(); using (var reader = new StreamReader(file.OpenReadStream())) { while (reader.Peek() >= 0) result.AppendLine(reader.ReadLine()); } return result; }
You may also have the async version:
public static async Task<string> ReadAsStringAsync(this IFormFile file) { var result = new StringBuilder(); using (var reader = new StreamReader(file.OpenReadStream())) { while (reader.Peek() >= 0) result.AppendLine(await reader.ReadLineAsync()); } return result.ToString(); }
Then you can use this version as follows:
public Task<List<string>> Index(IFormFile file) => file.ReadAsListAsync();
source share