我正在上传一个 Excel 文件并从中提取数据并将其保存到数据库中。我正在使用 MVC4 .NET 框架。这是我上课的代码:
public static void Upload(HttpPostedFileBase File)
{
NIKEntities1 obj = new NIKEntities1();
MyApp = new Excel.Application();
MyApp.Visible = false;
string extension = System.IO.Path.GetExtension(File.FileName);
string pic = "Excel" + extension;
string path = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Excel"), pic);
File.SaveAs(path);
MyBook = MyApp.Workbooks.Open(path);
MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
int lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
List<Employee> EmpList = new List<Employee>();
for (int index = 2; index <= lastRow; index++)
{
System.Array MyValues = (System.Array)MySheet.get_Range("A" +
index.ToString(), "B" + index.ToString()).Cells.Value;
EmpList.Add(new Employee
{
BatchID = MyValues.GetValue(1, 1).ToString(),
BatchName = MyValues.GetValue(1, 2).ToString()
});
}
for (int i = 0; i < EmpList.Count; i++)
{
int x=obj.USP_InsertBatches(EmpList[i].BatchID, EmpList[i].BatchName);
}
}
}
class Employee
{
public string BatchID;
public string BatchName;
}
此代码第一次运行良好,但下一次它说该文件当前正在使用中。所以我想使用以下行在代码末尾删除文件:
File.Delete(path);
但是这一行抛出了错误:
HttpPostedFileBase 不包含 Delete 的定义
另外,如果我不写这一行并再次尝试执行代码,它会说它无法保存,因为存在同名的文件并且无法替换,因为它当前正在使用中。
我应该怎么做才能摆脱这个:
(File.Delete()) Error
访问我收到的不保存的 Excel 文件的任何其他方式也将非常有帮助,因为我只需要访问一次数据。