Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

TextWriter encoding

1 view
Skip to first unread message

coder316

unread,
Dec 18, 2009, 12:34:54 PM12/18/09
to
Hello,
I'm trying to change the encoding for a textwriter:
TextWriter w = new StringWriter();

XmlTextWriter xmlWriter = new XmlTextWriter(w);
w.Encoding = System.Text.Encoding.Unicode;

But I'm getting an error

Property or indexer 'System.IO.TextWriter.Encoding' cannot be assigned
to -- it is read only

How do I change this?
Thanks

coder316

unread,
Dec 18, 2009, 12:45:03 PM12/18/09
to

I tried this too:

TextWriter w = new StringWriter();

XmlTextWriter xmlWriter = new XmlTextWriter(w);

Encoding unicode = Encoding.Unicode;
w.Encoding = unicode;

mick

unread,
Dec 18, 2009, 12:57:44 PM12/18/09
to

"coder316" <code...@gmail.com> wrote in message
news:0f471816-741b-4ff1...@l13g2000yqb.googlegroups.com...

I think you set up the encoding when you new up XmlTextWriter. Have a look
at the overloads for it.

mick

mick

unread,
Dec 18, 2009, 1:00:00 PM12/18/09
to

"coder316" <code...@gmail.com> wrote in message
news:e3e8be54-502d-4dbd...@o28g2000yqh.googlegroups.com...

I tried this too:

If Encoding is read-only you wont bet able to set it to anything. I imagine
it just tells you what encoding has been set, although thats just a guess as
Ive never used it myself.

mick

Jeff Johnson

unread,
Dec 18, 2009, 1:07:07 PM12/18/09
to
"coder316" <code...@gmail.com> wrote in message
news:0f471816-741b-4ff1...@l13g2000yqb.googlegroups.com...

You appear to be writing to a string (since you're using a StringWriter),
and strings are ALWAYS Unicode. The only time an encoding would come into
play would be when writing the string to a stream.

Also, by creating an XmlTextWriter directly, you're doing things "the old
way." From MSDN:

===============
In the .NET Framework version 2.0 release, the recommended practice is to
create XmlWriter instances using the XmlWriter.Create method and the
XmlWriterSettings class. This allows you to take full advantage of all the
new features introduced in this release. For more information, see Creating
XML Writers.

===============


Peter Duniho

unread,
Dec 18, 2009, 1:38:11 PM12/18/09
to

You don't change it. You provide the desired encoding when creating the
XmlTextWriter in the first place (by using a constructor that takes as
an argument the encoding, or by passing a TextWriter with the
appropriate encoding already set).

That said, in this case you are writing to a StringWriter, so you have
no choice of the encoding. Strings are always UTF-16, so the encoding
always winds up being UTF-16, no matter what encoding you tell
XmlTextWriter to use.

Pete

0 new messages