"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Einar Høst <_e*******@hotmail.com> wrote:
I'm having weird problems using StringWriter and XmlTextWriter. My code
looks like this:
StringWriter sw = new StringWriter(CultureInfo.InvariantInfo);
XmlTextWriter xtw = new XmlTextWriter(sw); // NullReferenceException
thrown here!
xtw.WriteStartDocument();
xtw.WriteStartElement("MyRoot");
/// Write some nodes.
xtw.WriteEndElement(); // MyRoot
xtw.WriteEndDocument();
xtw.Close();
string str = sw.ToString();
It's been working swell until now, and it still works from a test app I'm
using. However, when interacting with the real app we're developing, the
code now crashes at the second line - apparently XmlTextWriter's
constructor isn't too happy about the input its getting?
Hope someone can shed a bit of light on this - it's mighty dim at best to
me.
Note btw that everything works well if I omit the XmlTextWriter and write
everything to the StringWriter...
It seems very unlikely that it's really crashing there, although
obviously I wouldn't like to say for sure. If you put some other "new"
code in there (between the creation of the StringWriter and the
XmlTextWriter) can you step through that (and ensure that it does the
right thing)? It sounds like the kind of error which usually means the
debugger isn't debugging what it thinks it is.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Hi Jon, thanks for replying.
I found it very unlikely too, so it took me a while to find "the bug". I
still don't understand why it fails. However, I did some very brute
testing - quite simply throwing an exception before and after the new
XmlTextWriter(sw) statement, like this:
First test:
StringWriter sw = new StringWriter(CultureInfo.InvariantInfo);
throw new MyAppException("Einar's first exception");
XmlTextWriter xtw = new XmlTextWriter(sw); // NullReferenceException
thrown here!
Second test:
StringWriter sw = new StringWriter(CultureInfo.InvariantInfo);
XmlTextWriter xtw = new XmlTextWriter(sw); // NullReferenceException
thrown here!
throw new MyAppException("Einar's second exception");
For the first test, I caught "Einar's first exception", for the second, I
got the NullReferenceException as before. I should mention also that I get
some further information: "Value cannot be null. Parameter name: s". I did
some searching on the web, and found this url which didn't exactly enlighten
me, but did seem to discribe problems with using XmlTextWriter:
http://www.dotnet247.com/247referenc...34/174127.aspx
I find it very strange that something would be able to corrupt my managed
memory...?
Regards,
Einar.