尝试使用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;
}