0

I am trying to use XDocument for the first time, it seems like a great option. However after I open, modify, and Save, another (older VB6) application needs to be able to read the file, but can't, because there are some extra invisible bytes in the beginning of the file. See the attached screenshot here. Those 3 bytes were not there before I saved using XDocument. Here is the code, pretty simple.

XDocument xmlFile = XDocument.Load(outputFile);
var query = from c in xmlFile.Elements("LOG_CFG").Elements("LogControl").Elements("LogFileAttributes").Elements("LogFileName")
            select c;

foreach (XElement element in query)
{
    element.Value = GetLogCfgLogFileName(name);
}

xmlFile.Save(outputFile);

Some searching suggested I change the Save line to read:

using (var writer = new XmlTextWriter(outputFile, null))
{
    xmlFile.Save(writer);
}    

however that causes the file to lose formatting; the output file is all on a single line. It has something to do with saving to the same file that was loaded, because if I save to a 2nd file name, it works great.

Does anyone know if the extra bytes at the beginning are avoidable, and if not, suggest a useful pattern for opening, modifying, and saving back to the same file? I could go back to an XmlTextReader/Writer but I really love XDocument.

Dave Ludwig
  • 460
  • 1
  • 4
  • 14
  • The "extra bytes" are likely the BOM (Byte Order Mark). –  Oct 01 '12 at 23:33
  • http://stackoverflow.com/questions/4942825/xdocument-saving-xml-to-file-without-bom and http://stackoverflow.com/questions/159097/issue-with-xdocument-and-the-bom-byte-order-mark covers this aspect of the question; not the other question about "preserving formatting". Please ask a *single* question :) –  Oct 01 '12 at 23:35

0 Answers0