在服务器上创buildExcel文件后,如何自动删除Excel文件并将其返回给用户?

我正在Web服务器上创build一个Excel文件,使用OleDb连接物理文件(以及物理文件)和追加logging。 然后,我通过MVC向用户返回一个FilePathResult ,并希望由于对所附logging的数据保护问题而删除物理文件。

我曾尝试在Finally子句中使用File.Delete ,但是我得到一个File Not Found错误,这意味着当MVC尝试将文件发送给用户时文件已经消失。

我想创build文件作为一个MemoryStream,但我认为OleDb需要一个物理文件连接,所以这不是一个选项。

任何build议如何删除文件后,在一个操作中返回?

编辑

按要求,这是我工作,但我不知道它是如何帮助:)

Public Function ExportAllOutputs() As FilePathResult ' Create Export File Name Dim ExportFilename As String = Replace(Me.Name, " ", "_") & "_Outputs.xls" Try ' Create Export File CreateExportFile(ExportFilename) ' Populate Export File For Each OutputType As OutputTypeEnum In [Enum].GetValues(GetType(OutputTypeEnum)) ExportHelper.AppendOutputs(ExportFilepath & ExportFilename, Me.GetOutputs(OutputType), Me.ProgrammeID) Next ' Return Export File Return ReturnExportFile(ExportFilename) Catch ex As Exception Throw Finally 'If IO.File.Exists(ExportFilepath & ExportFilename) Then IO.File.Delete(ExportFilepath & ExportFilename) End Try End Function 

有点哈克,但你可以做如下:

  1. 使用File.ReadAllBytes()将文件读入内存中的字节数组,
  2. 删除文件,
  3. 在字节数组周围形成一个内存stream
  4. 使用FileStreamResult获取MVC通过stream返回数据。

显然,如果文件很大,那么你可能会受到内存压力。