XamlReader.Parse throws "Invalid character in this encoding"

I have a problem with the following code:

using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
    var content = reader.ReadToEnd();
    ParserContext context = new ParserContext()
    {
        BaseUri = new Uri(Configuration.SkinsFolder)
        //,XmlLang = "utf-8" // I have tried with this parameter and without it
    };
    var result = XamlReader.Parse(content, context);
    return result;
}

The corresponding xaml where the problem appears:

...
<TextBlock> </TextBlock>
<TextBlock Text="קח מספר" />
...

While parsing this xaml, I get an exception:

Invalid character in the given encoding. Line 76, position 167.
   at System.Windows.Markup.XamlReaderHelper.RethrowAsParseException(String keyString, Int32 lineNumber, Int32 linePosition, Exception innerException)
   at System.Windows.Markup.XamlReaderHelper.Read(XamlNode& xamlNode)
   at System.Windows.Markup.XamlParser.ReadXaml(Boolean singleRecordMode)
   at System.Windows.Markup.XamlParser._Parse()
   at System.Windows.Markup.XamlParser.Parse()

Xaml file saved as utf-8

Does anyone know how I can download this xaml without such problems? Thanks in advance!

PS: Well, I found the source of the problem.

The correct way to load xaml is to use the XamlReader.Load method instead of XamlReader.Parse. In my case, it looks like this:

using (Stream stream = new FileStream(source, FileMode.Open))
{
    ParserContext context = new ParserContext()
    {
        BaseUri = new Uri(Configuration.SkinsFolder)
    };
    var result = XamlReader.Load(stream, context);
    return result;
}

Thanks everyone!

+5
source share
1 answer

. , .NET Framework. XamlReader.Parse(, ):

public static object Parse(string xamlText, ParserContext parserContext)
{
  return System.Windows.Markup.XamlReader.Load((Stream) new MemoryStream(Encoding.UTF8.GetBytes(xamlText)), parserContext);
}
+4

All Articles