保存并删除使用HttpPostedFileBase保存的Excel文件

我正在上传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的定义

此外,如果我不写这行,并尝试再次执行代码,它说,它不能保存,因为一个文件存在相同的名称,并且因为它当前正在使用不能被replace。

我该怎么办才能摆脱这个:

  (File.Delete()) Error 

任何其他的方式来访问我没有保存的Excel文件也将是非常有用的,因为我只需要访问一次数据。

您使用的File是您的variables,它是您的方法的input参数。 该参数的typesHttpPostedFileBase并且该types没有实例方法 (也不是静态方法),允许您删除该File实例。

您可能正在查找System.IO命名空间中Filetypes的静态Delete方法。

一个quickfix将是明确你的意思是哪个File

 System.IO.File.Delete(path); 

尽pipe如此,您可能需要考虑一个不同的命名指南。 在C#中,我们倾向于写一个小写字母开头的variables。 框架中的几乎所有types都以大写字母开始。 这使得更容易区分事物filefiletypes。

请注意,只有在文件被所有进程closures且文件系统清除了所有文件句柄的情况下,文件才能被删除。 在你的情况下,你必须确保Excelclosures文件并释放它的句柄。 如果您的search索引器运行或粗略的病毒扫描器,您可能需要尝试几次才放弃。

我通常使用这个代码:

  // make sure here all Ole Automation servers (like Excel or Word) // have closed the file (so close the workbook, document etc) // we iterate a couple of times (10 in this case) for(int i=0; i< 10; i++) { try { System.IO.File.Delete(path); break; } catch (Exception exc) { Trace.WriteLine("failed delete {0}", exc.Message); // let other threads do some work first // http://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/ Thread.Sleep(0); } } 

从我可以告诉,你打开Excel,阅读文件,但从来没有closuresExcel。

加:

 MyApp.Workbooks.Close(); MyApp.Quit(); 

在上传function的末尾。 更好的是,包装整个代码

 try{ //here goes your current code } catch(Exception e) { //manage exception } finally { MyApp.Workbooks.Close(); MyApp.Quit(); } 

你在try catch块外面初始化MyApp,然后不pipe发生什么事closures文件。