Save and delete Excel file saved using HttpPostedFileBase

流过昼夜 提交于 2019-12-05 20:14:27

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.

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

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

System.IO.File.Delete(path);

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.

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.

I normally use this code:

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

From what I can tell, you are opening Excel, reading the file but never closing the Excel.

Add:

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

at the end of the Upload function. Even better, wrap whole code you got in

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

You initialize MyApp outside try catch block, then whatever happens close the file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!