0

Trying to read a string from a BinaryReader as following:

var req = HttpWebRequest.Create( url + context.Request.Url.Query + "&cql_filter=strSubstring(codigo,0,3)=%27" + 201 + "%27");
var resp =  req.GetResponse();
var stream = resp.GetResponseStream();
var br = new BinaryReader(stream);
var texto = br.ReadString();

But I get the title exception. Tried to solve it as mentioned here, but I can't do sizeof(String).

var count = br.BaseStream.Length / sizeof(String);
for (var i = 0; i < count; i++)
{
    string v = br.ReadString();
    texto = texto + v;
}

How can I solve this? Thanks!

teraxxx
  • 55
  • 1
  • 1
  • 10
  • From the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.io.binaryreader.readstring?view=netframework-4.8): "BinaryReader.ReadString Method Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.". Is your string in your stream prefixed with the length? If not then you can not use ReadString. – Longoon12000 Oct 31 '19 at 12:27
  • Also you can not use sizeof for strings because they are either \0 terminated or fixed-length but a string can be any size. You always have to know where the string ends, that's why ReadString requires the string length as prefix so it knows when to stop reading. – Longoon12000 Oct 31 '19 at 12:30
  • 1
    Did you try https://stackoverflow.com/questions/3273205/read-text-from-response ? – mjwills Oct 31 '19 at 12:31
  • 1
    Why are you using a BinaryReader at all? There was *another* malicious execution attack using it only 2 days ago - that class, and the BinaryFormatter class it uses, will serialize and deserialize *anything* - even classes and code that don't exist in the application. This happens because it writes type metatadata into its payolad. Which, BTW, means the resulting buffer is *bigger* than necessary – Panagiotis Kanavos Oct 31 '19 at 12:34
  • The de-facto standard is to use JSON with XML a close second. It's also standard for servers to use response compression, which means even with JSON or XML, the response is smaller than uncompressed binary. Finally, if you care about performance and size, use `protobuf`, and possibly gRPC. `protobuf` is pretty standard format while BinaryFormatter's output is not, and actually discouraged by MS itself – Panagiotis Kanavos Oct 31 '19 at 12:36
  • Are you using GeoServer? That's not a .NET application and *definitelly* doesn't use BinaryFormatter. It returns XML, JSON, CSV or Shapefiles, a binary file format created by ESRI in the 1990s. You can't read it with BinaryReader. There are .NET libraries that can work with it though. For all the other formats, .NET already has serializers, eg XmlSerializer, XDocument, JSON.NET, etc – Panagiotis Kanavos Oct 31 '19 at 12:42

0 Answers0