C# and XmlTextWriter sends some garbage.

  • Thread starter Thread starter Robert Dickow
  • Start date Start date
R

Robert Dickow

Hi,

My XML files created with XmlTextWriter routines has been resulting in
working files, but they include three bytes of garbage at the start of
the file.

The bytes are: $EF $BB $BF (I think it always outputs these)

I am using VS 2002 and C#.

My coding involves opening a file stream, then the XmlTextWriter...

------CODE FRAGMENT------------------
string xmlpath = Server.MapPath("../xmldata");

myXmlFile = System.IO.File.Create(xmlpath + "\\" + "myxmlfile.xml");
if (myXmlFile.CanWrite)
{
myXmlFile.Lock(0,4000);
myXmlFile.Flush(); // added to try a workaround for the 'bug'
myXmlFile.Position = 0; // reposition to start, workaround.
myXml = new XmlTextWriter(myXmlFile, System.Text.Encoding.UTF8);
myXml.Formatting = System.Xml.Formatting.Indented;
myXml.Indentation = 1;
myXml.IndentChar = (char) 9;
myXml.WriteStartDocument();
// _XmlNL();
myXml.WriteStartElement("Board");
----END FRAGMENT---------------------------

Actually, the files with the garbage display fine as raw files in IE on
Windows and in FireFox on Mac, but IE on Mac chokes on the file, giving
an error about the garbage.

Anybody know if this is a bug in the C# routines in .NET 1.1, or is it
just me?

Bob Dickow
 
Here I go answering my own question...

It looks like the XmlTextWriter will sometimes have garbage in its
buffer, so....

.........
myXml.Flush(); // do this before any output to xml file.

myXmlFileStreamHandle.Position = 0 // set file pointer to beginning.

.... all is ok now.
 
Robert Dickow said:
Hi,

My XML files created with XmlTextWriter routines has been resulting in
working files, but they include three bytes of garbage at the start of
the file.

The bytes are: $EF $BB $BF (I think it always outputs these)

I am using VS 2002 and C#.

Anybody know if this is a bug in the C# routines in .NET 1.1, or is it
just me?

Bob Dickow

Bob,

I cannot say this is a bug, but I can verify that in my files that are
generated using VS 2003 and .Net 1.1 I have the same bytes at the beginning
of my files.
 
Those three bytes represent the preamble used to indicate that the file is incoded in UTF8. The default UTF8 encoder accessed
through Text.Encoding.UTF8 outputs that preamble. To prevent those three bytes then create your own instance of UTF8Encoding.
The default for a new instance is to not emit a preamble set of bytes.

Kelly
 
Back
Top