V3222. Potential resource leak. An inner IDisposable object might remain non-disposed if the constructor of the outer object throws an exception.
The analyzer has detected a potential resource leak. If creating an object causes an exception, the inner object already created may not be properly released.
The example:
public void EditFile(string f)
{
using (BufferedStream os = new BufferedStream(new FileStream(f,
FileMode.Open)))
{
....
}
}
In this case, an object of the FileStream
class may be created successfully, but an exception is thrown when creating an object of the BufferedStrem
class. As a result, the Dispose
method is not be called, and the file descriptor is not released.
To secure the code, consider the following approach:
public void EditFile(string f)
{
using (FileStream fileStream = new FileStream(f, FileMode.Open))
{
using (BufferedStream os = new BufferedStream(fileStream))
{
....
}
}
}
In this implementation, the using
statement creates an object of the FileStream
class in advance, ensuring it is properly released and preventing the resource leak.
This diagnostic is classified as: