ChickenNugget
ChickenNugget

Reputation: 40

C# Stream.CanSeek property, This Stream Doesn't Support Seeking

Me and my friend are trying to send http request that we received from the client

            listener.Prefixes.Add("http://localhost:3294/discord/");
            listener.Start();

            Console.WriteLine("Listening...");
            HttpListenerContext context = listener.GetContext();

            Stream body = context.Request.InputStream;
            Encoding encoding = context.Request.ContentEncoding;
            StreamReader reader = new StreamReader(body, encoding);
            
            if (body != null)
            {
                byte[] buffer = new byte[body.Length];
                body.Read(buffer, 0, (int)body.Length);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://discord.com/api/webhooks/818198824439004692/jfe2zN93Ca0VOVry0uIBe6xvmx74tYP9QdaEFH--sDMSscKXcgxAYvlu3RSYwb32oZra");
                request.Method = "POST";
                request.ContentType = context.Response.ContentType;

                request.ContentLength = body.Length;
                Stream newStream = request.GetRequestStream();
                newStream.Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }

but I am getting an error System.NotSupportedException: 'This stream does not support seek operations.' when I try accessing body.Length and I noticed there is CanSeek property in Stream class but it is has only get. Is there a way to fix this?

Upvotes: 0

Views: 1419

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064224

You can't change a non-seekable stream to magically become seekable - in this case, the stream is the set of bytes arriving over the network (perhaps after some TLS/etc work). If you need the data to be seekable, you'll need to buffer (copy) it somewhere else (often a MemoryStream), and seek on that. The preferred option, however, is usually to remove the need to seek the data in the first place.

Upvotes: 3

Related Questions