private void btnSave_Click(object sender, EventArgs e)
{
if (_fileInfo != null && _allowSave )
{
_fileWatcher.EnableRaisingEvents = false;
byte[] data = Encoding.UTF8.GetBytes(atmlPreviewPanel.Text);
var fs = new FileStream(_fileInfo.FullName, FileMode.Truncate, FileAccess.Write);
using (fs)
{
//-------------------------------------------------------//
//--- Determine if the document is an XML document ---//
//--- If it is we'll load an XDocument with the ---//
//--- text and set some basic formatting instructions ---//
//--- and writing the value back out to the preview ---//
//--- window. This is done only for text formatting ---//
//--- purposes. ---//
//-------------------------------------------------------//
if (atmlPreviewPanel.Text.StartsWith("<?xml"))
{
string text = atmlPreviewPanel.Text.Trim();
using (var ms = new MemoryStream())
{
string byteOrderMarkUtf8 = Encoding.UTF8.GetString( Encoding.UTF8.GetPreamble() );
if (text.StartsWith( byteOrderMarkUtf8 ))
text = text.Remove( 0, byteOrderMarkUtf8.Length );
XDocument document = XDocument.Parse( text );
//------------------------------------------------------------------------------------//
//--- Set Basic Formatting Information - make sure the XML Declaration is included ---//
//------------------------------------------------------------------------------------//
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = false;
settings.Indent = true;
settings.NewLineOnAttributes = false;
settings.CloseOutput = true;
try
{
using (XmlWriter xmlWriter = XmlWriter.Create( ms, settings ))
{
int line = atmlPreviewPanel.CurrentPos;
document.Save( xmlWriter );
xmlWriter.Flush();
data = ms.ToArray();
atmlPreviewPanel.Text = Encoding.UTF8.GetString( data );
atmlPreviewPanel.CurrentPos = line;
}
}
catch (Exception)
{
LogManager.Error( "An error has occurred attempting to cleanup the XML file formatting." );
}
}
}
fs.Write(data, 0, data.Length);
fs.Close();
_fileWatcher.EnableRaisingEvents = true;
OnDocumentSaved(_fileInfo, data);
}
}
}