FileStream cannot be closed when an exception is occurred in runtime

The following is a part of my code:

try
{
    using (ExcelEngine excelEngine = new ExcelEngine())
    {
        .
        .
        .
        var path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Data\Temp", userId + ".xlsx");

        //Load the existing Excel workbook into IWorkbook
        FileStream inputStream = new FileStream(path, FileMode.Open);
        .
        .
        .
        //***For example, an exception is occurred here in runtime***
        .
        .
    }
}
catch(Exception ex)
{
    ...
}

I don’t have access to Close() method of FileStream in catch section.
I have to restart the server to close FileStream. How can I fix this?

>Solution :

Use the using statement for the filestream:

using var inputStream = new FileStream(path, FileMode.Open);

Leave a Reply