保存文件时发生System.IO.IO异常

时间:2018-07-17 13:10:35

标签: .net file model-view-controller ioexception

  

类型的异常:

     

mscorlib.dll中出现'System.IO.IOException',但未在用户代码中处理

     

其他信息:该进程无法访问文件'c:\ users \ ane \ documents \ visual studio 2015 \ Projects \ TestImportFromExcel \ TestImportFromExcel \ ContentItemsDetails_7_5_2018.xlsx',因为该文件正在被另一个进程使用。

发生在此行excelFile.SaveAs(path);

public ActionResult Import(HttpPostedFileBase excelFile)
{
    if (excelFile == null || excelFile.ContentLength == 0  )
    {
        ViewBag.Error = "select excel file <br/>";
        return View("Index");
    }
    else
    {
        if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx"))
        {
            string path = Server.MapPath("~/Content" + excelFile.FileName);
            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();
                int idNum= int.Parse(((Excel.Range)range.Cells[x, 1]).Text);
                i.Id = idNum;
                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");
        }
    }
}

0 个答案:

没有答案