I'm trying to return either a List or a null depending on the situation and I tried to do this using nullables, but I get NullReferenceException.
Here's the code:
ExcelProcess
public static class ExcelProcess<T>
{
public static Task<List<T>>? Upload(IFormFile file)
{
if(Check(file.FileName) == false)
{
return null;
}
return ProcessExcel(file);
}
private static bool Check(string fileName)
{
if (fileName.EndsWith(".xls") || fileName.EndsWith(".xlsx") || fileName.EndsWith(".csv"))
{
return true;
}
return false;
}
private static async Task<List<T>> ProcessExcel(IFormFile file)
{
List<T> records;
using (var reader = new StringReader(await ReadCsv(file)))
{
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
records = csv.GetRecords<T>().ToList();
}
}
return records;
}
private static async Task<string> ReadCsv(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();
}
}
Import
public async Task<IActionResult> ImportJudete(IFormFile file)
{
List<JudetRequest>? judeteExcel
= await ExcelProcess<JudetRequest>.Upload(file); //here I get the NullReferenceException and I get 500 Server Error
///....
}
Why am I getting this exception? Shouldn't it stop because that type is nullable?
Thanks.
>?` is a nullable Task that results in a non-nullable List of T. I think you intended `Task
– juunas May 24 '22 at 14:16?>`.
?> Upload(IFormFile file) still the same :)
– Octavian Niculescu May 24 '22 at 14:17