如何从ASP.NET Core中的IFormFile读入内存中的文本行的行?

Met*_*uru 22 parsing file-upload asp.net-core

说你有这个动作:

public List<string> Index(IFormFile file){

    //extract list of strings from the file
    return new List<string>();
}
Run Code Online (Sandbox Code Playgroud)

我已经找到了很多将文件保存到驱动器的示例,但是如果我想跳过这个并且只是直接从IFormFile读取文本行到内存中的数组怎么办?

Dav*_*ine 36

您应该能够执行以下操作:

public List<string> Index(IFormFile file) => file.ReadAsList();
Run Code Online (Sandbox Code Playgroud)

IFormFile有一个.OpenReadStream方法的抽象.

更新

为了防止大量不合需要的和可能很大的分配,我们应该一次读取一行并从每一行构建我们的列表.此外,我们可以将此逻辑封装在扩展方法中.该Index行动最终看起来是这样的:

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;
}
Run Code Online (Sandbox Code Playgroud)

相应的扩展方法如下所示:

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();
}
Run Code Online (Sandbox Code Playgroud)

同样你也可以有一个async版本:

public Task<List<string>> Index(IFormFile file) => file.ReadAsListAsync();
Run Code Online (Sandbox Code Playgroud)

然后你可以这样使用这个版本:

public List<string> Index(IFormFile file) => file.ReadAsList();
Run Code Online (Sandbox Code Playgroud)

更新2

IFormFile 版:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么将所有内容读入单个字符串,然后拆分并列出列表?为什么不逐行阅读并添加到列表呢?上面的代码分配了一个潜在的巨型字符串,然后分配了一个数组,然后分配了一个列表。 (2认同)
  • 好多了。垃圾收集器谢谢你。为了做得更好,我们需要知道消费者正在使用这些产品线做什么。也许他们不需要同时出现在一个列表中。 (2认同)

Alp*_*glu 13

ASP.NET Core 3.0 - 将表单文件的内容读入字符串

public static async Task<string> ReadFormFileAsync(IFormFile file)
{
    if (file == null || file.Length == 0)
    {
        return await Task.FromResult((string)null);
    }
    
    using (var reader = new StreamReader(file.OpenReadStream()))
    {
        return await reader.ReadToEndAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)