Question

I want to create an xml document and save it in string object.

I have refer both these question on SO for saving and encoding purpose

My code :

StringBuilder builder = new StringBuilder();

XDocument doc = new XDocument(new XElement("BANKID",
       new XElement("ReqID", "WEB"),
       new XElement("ReqHeader", "CASHDEP"),
       new XElement("CurrencyCode", ""),
       new XElement("CurrencyAbbrivation", "")));

using (TextWriter writer = new Utf8StringWriter(builder)) // Error Line
{
doc.Save(writer);
}
builder.ToString();

public class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding { get { return Encoding.UTF8; } }        
}

It gives me error saying "Utf8StringWriter does not contain a constructor that takes 1 arguments"

How to modify that class which would accept arguments as StringBuilder ?

Was it helpful?

Solution

Your custom Utf8StringWriter class has no constructor accepting a parameter, but you're trying to pass a value to it. That's why you're getting the error message.

Add a public constructor that accepts a StringBuilder, then pass it on to the base class:

public class Utf8StringWriter : StringWriter
{
    public Utf8StringWriter(StringBuilder stringBuilder)
        :base(stringBuilder)
    {
    }

    public override Encoding Encoding { get { return Encoding.UTF8; } }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top