0

尝试使用reportviewer 导出PDF 时出现此错误/异常 进程无法访问文件“xxx”,因为它正被另一个进程使用

public bool Export(string accountNumber, DateTime settlementDateTime, string PDFfileName, out string errorMsg)
    {
        bool success;
        ReportViewer reportViewer;
        Warning[] warnings;
        ReportParameter[] rptParameters;
        string[] streamids;
        string mimeType;
        string encoding;
        string filenameExtension;
        byte[] bytes;

        success = false;
        errorMsg = string.Empty;

        try
        {
            Console.Out.WriteLine(String.Format("Generando extracto para la cuenta \"{0}\" de la fecha {1}", accountNumber, settlementDateTime));
            reportViewer = new ReportViewer();

            // Set Processing Mode
            reportViewer.ProcessingMode = ProcessingMode.Remote;

            //set the URL of the report to execute
            reportViewer.ServerReport.ReportServerUrl = new Uri(repServerURL);
            reportViewer.ServerReport.ReportPath = repPath ;

            //Create the parameters that the report needs
            rptParameters = new ReportParameter[2];

            rptParameters[0] = new ReportParameter();
            rptParameters[0].Name = "rptPrm_AccountNumber";
            rptParameters[0].Values.Add(accountNumber);

            rptParameters[1] = new ReportParameter();
            rptParameters[1].Name = "rptPrm_Date";
            string dateAsString;

            dateAsString = settlementDateTime.ToString();
            rptParameters[1].Values.Add(dateAsString);

            reportViewer.ServerReport.SetParameters(rptParameters);

            // Process and render the report
            reportViewer.ServerReport.Refresh();

            //Render it to PDF and take the bytes to the FileStream
            bytes = reportViewer.ServerReport.Render(
                "PDF", null, out mimeType, out encoding, out filenameExtension,
                out streamids, out warnings);

            using (FileStream fs = new FileStream(Path.Combine(exportPath, PDFfileName), FileMode.Create))
            {
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
            }
            reportViewer.Dispose(); 

            success = true;
        }
        catch (Exception ex)
        {
            errorMsg = ex.Message;
            Console.Error.WriteLine(String.Format("Se presento error al generar extracto para la cuenta \"{0}\" de la fecha {1}-{2}", accountNumber, settlementDateTime, errorMsg));
        }

        return success;
    }
}

值得一提的是,在调用导出方法之前,我通过调用此方法删除文件夹中的所有 PDF 文件

 private bool DeletePDFfiles(StringBuilder sbLog)
    {
        bool exito;
        List<string> lstFiles;

        exito = true;
        lstFiles = new List<string>(Directory.GetFileSystemEntries(this.settings.folderWithFilesToSend, "*.pdf"));

        if ((lstFiles != null) && (lstFiles.Count > 0))
        {
            foreach (string existingPDFfile in lstFiles)
            {

                try
                {
                    File.Delete(existingPDFfile);
                }

                catch (Exception ex)
                {
                    //Si el archivo no pudo ser borrado 
                    sbLog.Append(string.Format("Error {0} al borrar el archivo {0}", ex.Message, existingPDFfile));
                    exito = false;
                }

            }
        }

        return exito;
    }
4

1 回答 1

0

通过设置 reportviewer = null 并在 catch 中添加 finally 来解决它

public bool Export(string accountNumber, DateTime settlementDateTime, string PDFfileName, out string errorMsg)
    {
        bool success;
        ReportViewer reportViewer;
        Warning[] warnings;
        ReportParameter[] rptParameters;
        string[] streamids;
        string mimeType;
        string encoding;
        string filenameExtension;
        byte[] bytes;
        FileStream fs ;

        success = false;
        errorMsg = string.Empty;
        fs = null ;    
        reportViewer = null ;

        try
        {
            Console.Out.WriteLine(String.Format("Generando extracto para la cuenta \"{0}\" de la fecha {1}", accountNumber, settlementDateTime));
            reportViewer = new ReportViewer();

            // Set Processing Mode
            reportViewer.ProcessingMode = ProcessingMode.Remote;

            //set the URL of the report to execute
            reportViewer.ServerReport.ReportServerUrl = new Uri(repServerURL);
            reportViewer.ServerReport.ReportPath = repPath ;

            //Create the parameters that the report needs
            rptParameters = new ReportParameter[2];

            rptParameters[0] = new ReportParameter();
            rptParameters[0].Name = "rptPrm_AccountNumber";
            rptParameters[0].Values.Add(accountNumber);

            rptParameters[1] = new ReportParameter();
            rptParameters[1].Name = "rptPrm_Date";
            string dateAsString;

            dateAsString = settlementDateTime.ToString();
            rptParameters[1].Values.Add(dateAsString);

            reportViewer.ServerReport.SetParameters(rptParameters);

            // Process and render the report
            reportViewer.ServerReport.Refresh();

            //Render it to PDF and take the bytes to the FileStream
            bytes = reportViewer.ServerReport.Render(
                "PDF", null, out mimeType, out encoding, out filenameExtension,
                out streamids, out warnings);

            fs = new FileStream(Path.Combine(exportPath, PDFfileName),FileMode.Create))
            fs.Write(bytes, 0, bytes.Length);
            success = true;
        }
        catch (Exception ex)
        {
            errorMsg = ex.Message;
            Console.Error.WriteLine(String.Format("Se presento error al generar extracto para la cuenta \"{0}\" de la fecha {1}-{2}", accountNumber, settlementDateTime, errorMsg));
        }
        finally
        {
            if(fs != null)
            {
                fs.Close(); 
            }
            if(reportViewer != null)
            {
                reportViewer.Dispose(); 
                reportViewer = null ;
            }
        }

        return success;
    }
}
于 2013-08-22T04:25:57.403 回答