Casey Crookston
Casey Crookston

Reputation: 13965

How to override timeout value on System.IO.Stream .OpenRead(): Getting ReadTimeout threw an exception of type 'System.InvalidOperationException'

I am trying to convert an Azure Cloud File into a stream:

System.IO.Stream stream = cloudFile.OpenRead();

That line throws this error:

ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

If I am reading this documentation properly ([Stream.ReadTimeout Property][1]), it looks like I should be able to override the default time out value, but I am not seeing how to do that. I've been looking at lots of other threads here about this:

C# Stream.ReadTimeout Property

C# Stream.Read with timeout

Stream Read/Write Timeout causes Invalid Operation Exception

... to name just a few. But so far I've not found a solution in any of them.

NOTE: Some of the threads I've read said this error will only happen in VS while debugging. But, we get the exact same error on the exact same line when this Azure Function app is published to Azure and executed in production.

My question is: How do I set the timeout value on OpenRead() to something longer than the default? (Or... am I looking at this wrong?)

Upvotes: 1

Views: 1776

Answers (2)

Jon
Jon

Reputation: 3255

Use the DownloadTextAsync() method to download the whole CSV file into a string, then you can do what you need with that

static async Task Main(string[] args)
{
        var url = "https://ihavenourl.com";
        var cloudFile = new CloudFile(new Uri(url));

        // Note you should use async/await properly but the OP requires non-async version
        var downloadedContents = cloudFile.DownloadTextAsync().GetAwaiter().GetResult();

        Console.WriteLine($"Downloaded the file contents {downloadedContents.Length} bytes");

        // TODO: Do something with the string contents
}

Upvotes: 1

Pedro Brito
Pedro Brito

Reputation: 263

I think that you need to apply the timeout in the OpenRead of the blob, like this

    cloudFile.OpenRead(null, new BlobRequestOptions() {
                ServerTimeout = TimeSpan.MaxValue,
                RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(5), 4), MaximumExecutionTime = TimeSpan.FromHours(3)
        });

Upvotes: 3

Related Questions