/// <summary> /// Inspect a file. /// </summary> /// <param name="inspectSourceFile">The file to inspect.</param> /// <param name="fixErrors">Option to fix errors that are found.</param> /// <returns>The number of errors found.</returns> public int InspectFile(string inspectSourceFile, bool fixErrors) { XmlTextReader reader = null; XmlWriter writer = null; LineInfoDocument doc = null; try { // set the instance info this.errors = 0; this.sourceFile = inspectSourceFile; // load the xml reader = new XmlTextReader(this.sourceFile); doc = new LineInfoDocument(); doc.PreserveWhitespace = true; doc.Load(reader); } catch (XmlException xe) { this.OnError(InspectorTestType.XmlException, null, "The xml is invalid. Detail: '{0}'", xe.Message); return(this.errors); } finally { if (null != reader) { reader.Close(); } } // inspect the document this.InspectDocument(doc); // fix errors if necessary if (fixErrors && 0 < this.errors) { try { using (StreamWriter sw = File.CreateText(inspectSourceFile)) { writer = new XmlTextWriter(sw); doc.WriteTo(writer); } } catch (UnauthorizedAccessException) { this.OnError(InspectorTestType.UnauthorizedAccessException, null, "Could not write to file."); } finally { if (null != writer) { writer.Close(); } } } return(this.errors); }
/// <summary> /// Inspect a file. /// </summary> /// <param name="sourceFile">The file to inspect.</param> /// <param name="fixErrors">Option to fix errors that are found.</param> /// <returns>The number of errors found.</returns> public int InspectFile(string sourceFile, bool fixErrors) { XmlTextReader reader = null; XmlWriter writer = null; LineInfoDocument doc = null; try { // set the instance info this.errors = 0; this.fixable = true; this.sourceFile = sourceFile; // load the xml reader = new XmlTextReader(this.sourceFile); doc = new LineInfoDocument(); doc.PreserveWhitespace = true; doc.Load(reader); } catch (XmlException xe) { this.OnError(InspectorTestType.XmlException, null, "The xml is invalid. Detail: '{0}'", xe.Message); return this.errors; } finally { if (null != reader) { reader.Close(); } } // inspect the document this.InspectDocument(doc); // fix errors if necessary if (fixErrors && 0 < this.errors) { if (this.fixable) { try { using (StreamWriter sw = File.CreateText(sourceFile)) { writer = new XmlTextWriter(sw); doc.WriteTo(writer); } } catch (UnauthorizedAccessException) { this.OnError(InspectorTestType.UnauthorizedAccessException, null, "Could not write to file."); } finally { if (null != writer) { writer.Close(); } } } else { this.OnVerbose(null, "Because this file contains \\r or \\n as part of a text or CDATA node, it cannot be automatically fixed."); } } return this.errors; }