Home > Back-end >  What is the correct way to handle to read output of web api stream from c# client
What is the correct way to handle to read output of web api stream from c# client

Time:06-13

    [HttpGet]
    [Route("stream/{filePath}")]
    public System.IO.Stream ReadStreamFromFile(string filePath)
    {
        return new System.IO.MemoryStream(System.IO.File.ReadAllBytes(filePath));
    }

Now I wanto to know how to read stream in C# client which is a generic way to get output and as currently supports string type.

           // Get response      
        using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream           
            StreamReader responseStream = new StreamReader(webresponse.GetResponseStream());
            response = responseStream.ReadToEnd();
        }

Please suggest.

Regards, amaR

CodePudding user response:

You can use HttpClient for sending request and then get the response as stream like this:

var client= new HttpClient();

var response= await client.GetAsync("url");

var stream= await response.Content.ReadAsStreamAsync();

By the way, for using HttpClient I recommend to read this: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0

CodePudding user response:

byte[] byteArray = Encoding.ASCII.GetBytes( test );
MemoryStream stream = new MemoryStream( byteArray );

By using above code, you will be able to get stream.

  • Related