I have function who take FilePath and return all of Excel information into a List.
My actual problem is not the function, but the error system who don’t work if my FilePath is bad or file not exist.
I try some error basic catch, but it’s not work and my program crash with this message :
System.NullReferenceException : ‘Object reference not set to an instance of an object.’
I paste my functions here :
public List<ImportExcelModel> GetList(string filePath)
{
List<ImportExcelModel> ExcelList = new List<ImportExcelModel>();
try
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
FileInfo fileInfo = new FileInfo(filePath);
using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.FirstOrDefault();
int totalColumn = worksheet.Dimension.End.Column; // <- Error Message is print here
int totalRow = worksheet.Dimension.End.Row;
for (int row = 2; row <= totalRow; row++)
{
ImportExcelModel ll = new ImportExcelModel();
for (int col = 1; col <= totalColumn; col++)
{
if (col == 1) ll.DPT = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 2) ll.Description = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 3) ll.Conditionnement = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 4) ll.StockInitial = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 5) ll.Entree = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 6) ll.Sortie = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 7) ll.StockMini = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 8) ll.StockReel = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
if (col == 9) ll.Localisation = worksheet.Cells[row, col].Value == null ? string.Empty : worksheet.Cells[row, col].Value.ToString();
}
ExcelList.Add(ll);
}
}
return ExcelList;
}
catch (Exception ex)
{
return ExcelList;
}
}
Edit : Yes, I want empty list if I can’t open file
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
System.IO.File.Exists(path) will return true/false. Use this to find out if the file exists or not
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0