views:

37

answers:

1

Hello,

I am creating an Excel file on a web server, using OleDb to connect the the physical (well as physical as it can be) file and appending records. I am then returning a FilePathResult to the user via MVC, and would like to delete the physical file afterwards due to data protection concerns over the appended records.

I have tried using a File.Delete in a Finally clause but I get a File Not Found error which must mean the file has gone when MVC is trying to send the file to the user.

I thought about creating the File as a MemoryStream but I think OleDb needs a physical file to connect to so this isn't an option.

Any suggestions on how to delete the file after returning it in one operation?

Edit

As requested this is what I'm working from, though I'm not sure how it helps :)

    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

Thanks

+1  A: 

Somewhat hacky, but you could do as below:

  1. read the file into a byte array in memory using File.ReadAllBytes(),
  2. delete the file,
  3. form a memory stream around the byte array
  4. get MVC to return data via the stream using FileStreamResult.

Clearly, if the files are large then you may get memory pressures.

Neil Moss
Hi Neil, that makes perfect sense - create the real file using ADO - THEN read it into a Memory Stream - then delete it - so simple :) Cheers for that
David A Gibson