How to read in-memory lines of a text file from IFormFile in ASP.NET Core?

Let's say you have this action:

public List<string> Index(IFormFile file){ //extract list of strings from the file return new List<string>(); } 

I found many examples of saving a file to disk, but what if I instead want to skip this and just read the lines of text into an array in memory, right from the IFormFile?

+22
source share
1 answer

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(); 
+35
source

Source: https://habr.com/ru/post/1258212/


All Articles