Recently I was trying to build an app that can read excel files. But just after I select the .xls file I get an error saying this:(i am trying to read the source raw .xls file locally after saving it from FTP Server)
e.Message = "Invalid file signature." at line using (var reader = GetExcelReader(stream, file))
NOTE : Yes those .xls files are completely opening in miscrosoft excel as well in wps office but when i open those source .xls files in the ftp server and again those as save as .xls put it again in ftp server it works pefectly and even my ExcelDataReader library is readding it properly. i Mean why there is a need to again saving as .xls to get it read through ExcelDataReader library . Are those soursr .xls files corrupt? but why those opening perfeclty in my system
My Code :
using ExcelDataReader;
var latestFiles = GetLatestXlsxFilesFromFtp(ftpServerUrl, ftpUsername, ftpPassword, folderPath);
// Reading XLS files and updating the database
using (var dbContext = new MyDbContext())
{
try
{
foreach (var fileTuple in latestFiles)
{
string file = fileTuple.Item1;
int associatedValue = fileTuple.Item2;
using (WebClient ftpClient = new WebClient())
{
var ftpUri = new Uri(new Uri(ftpServerUrl), folderPath + file);
var localFilePath = Path.Combine(Path.GetTempPath(), file.ToString());
ftpClient.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
ftpClient.DownloadFile(ftpUri, localFilePath);
using (var stream = File.Open(localFilePath, FileMode.Open, FileAccess.Read))
{
Console.WriteLine($"File Length: {stream.Length} bytes");
//getting error here going into ctach block e.Message = "Invalid file signature."
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var dataSet = reader.AsDataSet();
DataTable dataTable = dataSet.Tables[0];
Type modelType = GetModelTypeFromFile(file);
var dynamicDbSet = dbContext.Set(modelType);
bool skipFirstRow = true;
foreach (DataRow row in dataTable.Rows)
{
if (skipFirstRow)
{
skipFirstRow = false;
continue; // Skip the first row
}
var record = Activator.CreateInstance(modelType);
MapPropertiesFromExcelRow(row, modelType, record, dataTable.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToList());
SetPropertyValues(record, "SourceFile", file);
SetPropertyValues(record, "SourceFileId", associatedValue);
dynamicDbSet.Add(record);
}
}
}
}
}
dbContext.SaveChanges();
//Ignore brackets here i havent closed brackets perfectly here but those are done in my code ..;)