Search code examples
c#excelexceldatareader

C# ExcelDataReader Invalid File Signature


I've already looked at this and it did not solve my issue https://stackoverflow.com/questions/51079664/c-sharp-error-with-exceldatareader

I've tried building a method that reads an XLS file and converts it to string[] But I get an error when trying to run it: ExcelDataReader.Exceptions.HeaderException: Invalid file signature.

I have tried running it with XLSX and it works fine

The files that I am using have worked before

Note. I have run the same method that worked with XLS before, so I'm confused as to why this error is occurring.(using ExcelDataReader Version 3.6.0)

Here is the code:


private static List<string[]> GetExcelRecords(string path, bool hasHeaders)
        {
            var records = new List<string[]>();
            using (var stream = File.Open(path, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    var sheetFile = reader.AsDataSet().Tables[0];

                    for (int i = 0; i < sheetFile.Rows.Count; i++)
                    {
                        var record = sheetFile.Rows[i];
                        if (hasHeaders)
                        {
                            hasHeaders = false;
                            continue;
                        }
                        var row = record.ItemArray.Select(o => o.ToString()).ToArray();
                        records.Add(row);
                    }
                }
            }
            return records;
        }

The exception occurs on line 4

I have tried using ExcelReaderFactory.CreateBinaryReader and ExcelReaderFactory.CreateOpenXlmReader


Solution

  • The problem appears that my laptop is corrupting XLS files (I'm unsure why) The error isn't due to the file type, but instead the fact that my files are corrupted.