如何知道方法何时在控制器中完成

How to know when a method finish in controller

我对这种方法有疑问,我想 return 一个 PDF 文件,当方法结束时,我想从目录中删除 de 文件。

public ActionResult DescargaPdfCompara(string id)
    {
        var rutaPdf = string.Empty;
        var type = "application/pdf";

        try
        {

            DateTime ahora = DateTime.Now;
            var numeroAleatorio = new Random();
            int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
            string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");

            var result = SimuModel.ObtenerSabanaReporteComparativo(id);
            var resumen = SimuModel.ObtenerPreExcel(result);
            SimuModel.GenerarPdfCompa(result, resumen, Ruta);

            rutaPdf = Ruta;

            return File(rutaPdf, type);

        }
        catch (Exception e)
        {

            throw e;
        }
        finally
        {
            System.IO.File.Delete(rutaPdf);
        }
    }

最后我删除了文件,但由于该方法找不到该文件而出现错误,出于某种原因,该方法在 return 之前删除了文件。

PD:抱歉我的英语不好,我来自智利。

感谢您的回答!

更改 return 类型 ContentResult

最后删除部分。

public ContentResult DescargaPdfCompara(string id)
{
    var rutaPdf = string.Empty;
    var type = "application/pdf";

    try
    {

        DateTime ahora = DateTime.Now;
        var numeroAleatorio = new Random();
        int numeroRandomico = numeroAleatorio.Next(100000000, 1000000000);
        string Ruta = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Reportes\" + Convert.ToString(ahora.Year + ahora.Month + ahora.Day + ahora.Hour + ahora.Minute + ahora.Second + numeroRandomico) + ".pdf");

        var result = SimuModel.ObtenerSabanaReporteComparativo(id);
        var resumen = SimuModel.ObtenerPreExcel(result);
        SimuModel.GenerarPdfCompa(result, resumen, Ruta);

        rutaPdf = Ruta;

        return Content(rutaPdf, type);

    }
    catch (Exception e)
    {

        throw e;
    }

}

您可以使用 System.IO.File.ReadAllBytes 将所有文件内容读入内存,然后删除文件和 return 使用 Controller.File 方法的另一个重载的内容:

    public ActionResult GetFile()
    {
        var fileName = Path.GetTempFileName();
        System.IO.File.WriteAllText(fileName, "Hola, Chile!");
        var bytes = System.IO.File.ReadAllBytes(fileName);
        System.IO.File.Delete(fileName);
        return File(bytes, "text/plain", "file.txt");
    }