首页 > 解决方案 > 保存文件时发生 System.IO.IO 异常

问题描述

类型的例外:

“System.IO.IOException”发生在 mscorlib.dll 中,但未在用户代码中处理

附加信息:该进程无法访问文件 '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");
        }
    }
}

标签: .netfilemodel-view-controllerioexception

解决方案


推荐阅读