pthalacker pthalacker - 1 month ago 15
C# Question

Why does a MemoryStream throw an InvalidFormatException?

I have the following lines of code

var input = "<x";
var ms = new MemoryStream();
var test = System.Text.Encoding.UTF8.GetBytes(input);
ms.Write(test, 0, test.Length);
var sut = new Web.Transpiler.Transpiler();
var rs = await sut.TranspileAsync(ms);


The last line throws a FormatException with the following in the stack.

at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Byte.Parse(String s, NumberStyles style, NumberFormatInfo info)
at MyProject.Transpiler.<TranspileAsync>d__4.MoveNext()
in C:\Users\thala\Documents\Projects\my-project\MyProject\Transpiler\Transpiler.cs:line 22


Can someone tell me what I am doing wrong?

Answer

After writing to a memory stream, you should seek the start again when reading from it, like so:

ms.Seek(0, SeekOrigin.Begin);

Though I guess it's your Transpiler throwing the invalidoperation exception