gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 20:48:05 25 4
gpt4 key购买 nike

我正在 Web 服务器上创建一个 Excel 文件,使用 OleDb 连接物理(以及可以是物理的)文件并附加记录。然后我返回一个 文件路径结果 通过 MVC 发送给用户,并且由于对附加记录的数据保护问题,想在之后删除物理文件。

我试过使用 文件.删除最后子句,但我得到一个 File Not Found 错误,这一定意味着当 MVC 试图将文件发送给用户时文件已经消失。

我考虑过将文件创建为 MemoryStream,但我认为 OleDb 需要一个物理文件来连接,所以这不是一个选项。

关于在一次操作中返回文件后如何删除文件的任何建议?

编辑

根据要求,这就是我的工作,尽管我不确定它有什么帮助:)

    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

最佳答案

有点hacky,但您可以执行以下操作:

  • 使用 File.ReadAllBytes() 将文件读入内存中的字节数组,
  • 删除文件,
  • 围绕字节数组
  • 形成内存流
  • 使用 FileStreamResult 让 MVC 通过流返回数据。

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

    关于.net - 如何在服务器上创建 Excel 文件并将其返回给用户后自动删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2927882/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com