导入 excel 文件 mcv 代码时发生 NullReferenceException

NullReferenceException happen while importing an excel file mcv code

我在导入方法的开头打了一个断点,代码总是进入 第一个条件,即使我导入了一个 excel 文件,这会导致 异常,异常说 'System.NullReferenceException' 类型的异常发生在 TestImportFromExcel.dll 但未在用户代码中处理

附加信息:未将对象引用设置为对象的实例。

  public ActionResult Import(HttpPostedFileBase excelFile)
    {

            if (excelFile.ContentLength == 0 || excelFile == null)
            {
                ViewBag.Error = "select excel file <br/>";
                return View("Index");
            }

            else
            {
                //if file is not null
                if (excelFile.FileName.EndsWith("xls") || 
                  excelFile.FileName.EndsWith("xlsx"))
                {
                    string path = Server.MapPath("~/Content" + 
                       excelFile.FileName);
                    if (System.IO.File.Exists(path))
                    {
                        System.IO.File.Delete(path);

                    }
                    excelFile.SaveAs(path);
                    Excel.Application application = new Excel.Application();

                    Excel.Workbook workBook = 
                    application.Workbooks.Open(path);
                    Excel.Worksheet worksheet = workBook.ActiveSheet;
                    Excel.Range range = worksheet.UsedRange;
                    List<ItemDetails> itemDetails = new List<ItemDetails>();
                    for (int x = 1; x < range.Rows.Count; x++)
                    {
                        ItemDetails i = new ItemDetails();
                        i.Id = ((Excel.Range)range.Cells[x, 1]).Text;
                        i.Factory = ((Excel.Range)range.Cells[x, 2]).Text;
                        i.ItemCode = ((Excel.Range)range.Cells[x, 3]).Text;
                        i.Description = ((Excel.Range)range.Cells[x,4]).Text;
                        i.UnitMeasure = ((Excel.Range)range.Cells[x,5]).Text;
                        i.Weight = ((Excel.Range)range.Cells[x, 6]).Text;
                        itemDetails.Add(i);
                    }
                    ViewBag.itemDetails = itemDetails;
                    return View("Success");
                }
                else
                {
                    ViewBag.Error = "the file type is not correct<br/>";
                    return View("Index");
                }
            }
        }
if (excelFile.ContentLength == 0 || excelFile == null)

需要

if (excelFile == null || excelFile.ContentLength == 0)

这样,如果第一个条件已经是 trueContentLength 属性 就不会被评估。