Search code examples
c#wpffilestreamsyncfusion

How to close FileStream without causing an error in "Syncfusion.PdfViewer"?


I'm using Syncfusion.PdfViewer in my project. When I click an item in a list, the related pdf file is loaded and shown in the PdfViewer:

private void PdfReport(string address)
{
    //Load the stream from the local system.
    FileStream fs = new FileStream(address, FileMode.Open);
    PdfSource = fs;
}

The problem is that each time I load a pdf file, a new instance of FileStream is created and the memory usage increases. When I try to close FileStream like the following code, the pdf is not shown in the viewer:

private void PdfReport(string address)
{
    //Load the stream from the local system.
    FileStream fs = new FileStream(address, FileMode.Open);
    PdfSource = fs;
    fs.Dispose();
}

How can I solve this problem?


Solution

  • You should check if a PdfSource exists and if so close/ dispose that before creating the new filestream, so just

    if (PdfSource is not null)
        PdfSource.Dispose();
    
    PdfSource = new FileStream(address, FileMode.Open);