保存和删除使用HttpPostedFileBase保存的Excel文件 [英] Save and delete Excel file saved using HttpPostedFileBase

查看:644
本文介绍了保存和删除使用HttpPostedFileBase保存的Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在上传一个Excel文件,并从中提取数据并将其保存到数据库中.我正在使用MVC4 .NET Framework.这是我来自班级的代码:

I am uploading an Excel file and extracting data from that and saving it into a database. I am using MVC4 .NET Framework. This is my code from class:

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

此代码在第一次时运行良好,但在下一次说该文件当前正在使用时.因此,我想到了使用以下行在代码末尾删除文件:

This code is working perfectly the first time but next time it says that file is currently in use. So I thought of deleting the file at the end of code using the following line:

File.Delete(path);

但是这一行抛出了错误:

But this line threw error:

HttpPostedFileBase不包含删除的定义

HttpPostedFileBase does not contain definition for Delete

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

Also, if I don't write this line and try to execute code again it says that it can't save because a file exists with same name and could not be replaced because it is currently in use.

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

What should I do to get rid of this:

  (File.Delete()) Error

以其他方式访问我所接收的Excel文件而不保存的其他方式也将非常有帮助,因为我只需要一次访问数据.

Any other way of accessing the Excel file which I am receiving without saving will also be very helpful because I have to just access the data one time.

推荐答案

您使用的File是您的变量,它是方法的输入参数.该参数的类型为 HttpPostedFileBase 并且该类型没有实例方法(对此也不是静态方法),可让您删除该File实例.

The File you use there is your variable that is the input parameter of your method. That parameter is of type HttpPostedFileBase and that type has no instance methods (nor static ones for that matter) that allow you to delete that File instance.

您可能正在寻找静态System.IO名称空间中File类型的"nofollow"> Delete 方法.

You are probably looking for the static Delete method on the File type that is in the System.IO namespace.

要明确指出您要指的是哪个File:

A quickfix would be to be explicit about which File you mean:

System.IO.File.Delete(path);

不过,您可能想为变量考虑一个不同的命名准则.在c#中,我们倾向于编写以小写字母开头的变量.框架中几乎所有类型都以大写字母开头.

You might want to consider a different naming guideline for your variables though. In c# we tend to write variables starting with a lower case letter. Almost all types in the framework start with an Uppercase letter. Which makes it easier to distinguish the thing file and the type File.

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

Do notice that a file can only be deleted if it is closed by all processes and all file handles are cleared by the filesystem. In your case you have to make sure Excel closed the file and released it's handles. If you have the search indexer running or a rough virus scanner you might have to try a few times before giving up.

我通常使用以下代码:

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

这篇关于保存和删除使用HttpPostedFileBase保存的Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆