Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 保存和删除使用HttpPostedFileBase保存的Excel文件_C#_Excel_Asp.net Mvc 4_Httppostedfilebase - Fatal编程技术网

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

C# 保存和删除使用HttpPostedFileBase保存的Excel文件,c#,excel,asp.net-mvc-4,httppostedfilebase,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;

我上传了一个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;
    }
但这一行出现了错误:

HttpPostedFileBase不包含删除的定义

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

我应该怎么做才能摆脱这个问题:

  (File.Delete()) Error

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

您使用的
文件中有一个变量,它是您方法的输入参数。该参数的类型为,并且该类型没有允许您删除该
文件
实例的参数(也没有静态参数)

您可能正在
System.IO
命名空间中的
文件
类型上查找静态方法

快速修复将明确说明您指的是哪个
文件

System.IO.File.Delete(path);

您可能需要考虑变量的命名规则。在c#中,我们倾向于写以小写字母开头的变量。框架中几乎所有类型都以大写字母开头。这使得区分

文件
和类型
文件
更容易

请注意,只有当文件被所有进程关闭并且文件系统清除了所有文件句柄时,才能删除该文件。在您的情况下,您必须确保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);
     }
 }
//在此处确保所有Ole自动化服务器(如Excel或Word)
//已关闭文件(因此关闭工作簿、文档等)
//我们迭代了几次(本例中为10次)
对于(int i=0;i<10;i++)
{
尝试
{
System.IO.File.Delete(路径);
打破
}捕获(异常exc)
{
WriteLine(“删除{0}失败”,exc.Message);
//让其他线程先做一些工作
// http://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/
睡眠(0);
}
}

据我所知,您正在打开Excel,读取文件,但从未关闭Excel

加:

在上传功能的末尾。更妙的是,把你得到的全部代码包装起来

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

在try catch块外初始化MyApp,然后不管发生什么都关闭文件

那样做了。在我的例子中,最后一部分,你放了一个从1到10的循环,这不是必需的。我只是在最后关闭了工作簿,然后删除了那个文件
MyApp.Workbooks.Close();
MyApp.Quit();
try{
  //here goes your current code
}
catch(Exception e)
{
 //manage exception
}
finally
{
MyApp.Workbooks.Close();
MyApp.Quit();
}