Search code examples
c#dotnet-httpclient

C# Download Partial Video Live Stream


I want to download 10 seconds video from live streaming but it has no file output when I do cts.Cancel().

I'm using .NET Framework 4.7.2

CancellationTokenSource cts = new CancellationTokenSource();;
...
var httpClient = new HttpClient();
var httpResult = await httpClient.GetAsync("http://.....video.flv", cts.Token);
var resultStream = await httpResult.Content.ReadAsStreamAsync();
var fileStream = File.Create(saveDir);
resultStream.CopyTo(fileStream);

Solution

  • found the solution I have to add HttpCompletionOption.ResponseHeadersRead to GetAsync and add cts.Token to CopyToAsync

    using (HttpClient client = new HttpClient())
    {
        using (HttpResponseMessage response = await client.GetAsync(videoUrl, HttpCompletionOption.ResponseHeadersRead))
        using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
        {
            using (Stream streamToWriteTo = File.Open(filename, FileMode.Create))
            {
                await streamToReadFrom.CopyToAsync(streamToWriteTo, 81920, cts.Token);
            }
        }
    }