False positive with C# using - Refactor this code to make sure 'stream' is disposed only once - csharpsquid:S3966

  • SonarQube Enterprise Edition Version 8.3.1 (build 34397)
  • minimal code sample to reproduce (.NET Core 3.1, C#8):
        {
            await using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"ThePath.{path}");
            using var reader = new StreamReader(stream); // Refactor this code to make sure 'stream' is disposed only once.

            return await reader.ReadToEndAsync().ConfigureAwait(false);
        }

This seems wrong - Dispose on the stream reader will not dispose the stream.

With the ‘old’ C# syntax the S3966 warning is not shown,

        internal static async Task<string> ReadDataFromFileAsync(string path)
        {
            await using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream($"ThePath.{path}");
            using (var reader = new StreamReader(stream))
                return await reader.ReadToEndAsync().ConfigureAwait(false);
        }

Hello @belgaard,

Your first example is actually a true positive and the rule should be triggered. using var stream will dispose the stream. using var reader will dispose the reader. And disposing the reader will also dispose the underlying stream for the second time.

You need to use leaveOpen argument to avoid that:

using var reader = new StreamReader(stream, leaveOpen: true);

The second example is a False Negative case due to the return statement. Same issue should be raised here as well. I’ve updated our older issue to track it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.