I'm needing to create a file validator that can check if the file type is correct. Originally we were just checking the content-type of the request, but as always our testers have managed to get around the restriction by simply changing the file extension of in the case an exe file to .csv which can fool our straightforward check.
This is what I have so far in the validator
private bool IsCorrectFileType(IFormFile file)
{
using var reader = new StreamReader(file.OpenReadStream());
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
try
{
csv.Read();
csv.ReadHeader();
List<string> headers = csv.Context.HeaderRecord.ToList();
}
catch (Exception _)
{
return false;
}
return true;
}
What I was intending on doing is if the CSV reader couldn't find the headers in the file then I was hoping it would blow up and return false but what's happening is the full content of the file is being read in as a single header in all non-csv file type situations. causing it to think that it was indeed a valid csv file and return true.
I cannot for the life of me work out a way to catch if the CSV file is indeed valid as in most cases the CSV reader can read in all the streams as byte data and the context of the header record looks like a valid CSV in this case.
What's annoying as well as much as we will never be uploading a file with a single header it feels dumb to just do a standard count on the headers to see if it has just one header to catch this issue.