I want to load data from a JSON file, but it could also be gzipp’ed, so I want to over another method that would just call the method for loading the JSON.
However, without await foreach
, the method returns immediately, Dispose()
is called on my Stream
and I get an exception that the file has been closed.
Is there a nicer way to write this?
Here’s my (simplified) code:
public async IAsyncEnumerable<Foo> GetDataFromCompressedJson(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var zip = new GZipStream(stream, CompressionMode.Decompress))
{
await foreach (var foo in GetDataFromJson(zip))
{
yield return foo;
}
}
}
public async IAsyncEnumerable<Foo> GetDataFromJson(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException(nameof(path));
}
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
await foreach (var foo in GetDataFromJson(stream))
{
yield return foo;
}
}
}
public async IAsyncEnumerable<Foo> GetDataFromJson(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
var data = System.Text.Json.JsonSerializer.DeserializeAsyncEnumerable<Foo>(stream);
await foreach (var foo in data)
{
yield return organizationInfo;
}
}