c# - 保存和删除使用 HttpPostedFileBase 保存的 Excel 文件

标签 c# excel asp.net-mvc-4 httppostedfilebase

我正在上传一个 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 does not contain definition for Delete

另外,如果我不写这一行并尝试再次执行代码,它会说它无法保存,因为存在同名文件并且无法替换,因为它当前正在使用中。

我应该怎么做才能摆脱这种情况:

  (File.Delete()) Error

访问我收到的不保存的 Excel 文件的任何其他方式也将非常有帮助,因为我必须只访问一次数据。

最佳答案

您在那里使用的 File 是您的变量,它是您的方法的输入参数。该参数的类型为 HttpPostedFileBase那个类型没有 instance methods (也不是静态的)允许您删除该 File 实例。

您可能正在寻找静态 Delete System.IO 命名空间中的 File 类型的方法。

快速修复是明确说明您指的是哪个 File:

System.IO.File.Delete(path);

不过,您可能需要为变量考虑不同的命名准则。在 C# 中,我们倾向于编写以小写字母开头的变量。框架中的几乎所有类型都以大写字母开头。这使得区分事物 file 和类型 File 变得更容易。

请注意,只有当文件被所有进程关闭并且所有文件句柄都被文件系统清除时,文件才能被删除。在您的情况下,您必须确保 Excel 关闭了文件并释放了它的句柄。如果您正在运行搜索索引器或粗糙的病毒扫描程序,您可能需要尝试几次才能放弃。

我通常使用这段代码:

 // 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);
     }
 }

关于c# - 保存和删除使用 HttpPostedFileBase 保存的 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32738029/

相关文章:

c# - 基于机会/权重返回随机值的容器

c# - 如果为 TestFixture 级别设置了 "Property"属性,是否有可能获得 Nunit "Property"属性值

c# - 如何为应用程序和迁移使用单独的连接字符串?

excel - 将 2 个 Excel 表合并为一个 append 数据?

python - Arelle 使用 Python 自动化将数据传输到 Excel 的小程序

wcf-web-api - ASP.NET Web API 绑定(bind)方法

asp.net-mvc - 如何根据用户在MVC 4中过滤结果

c# - ASP.NET 使用 Twitter 按钮登录 - 如果已经通过身份验证,如何停止要求用户进行身份验证?

excel - 使用自定义格式在excel中将负值显示为0

javascript - 如何通过路由值将 JSON 数组发送到操作方法 (MVC 4)