/// <summary>
/// Saves the <see cref="HtmlDocument"/> to the specified path.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="node">The <see cref="HtmlNode"/> to save.</param>
/// <param name="encoding">The encoding to use when writing the file.</param>
/// <seealso cref="HtmlNode"/>
/// <see cref="HtmlDocument"/>
public static void Save(string path, HtmlNode node, Encoding encoding)
{
if (path == null || node == null)
{
DebugBreakOrThrow("Figure out why " + (path == null ? "path" : "node") + "is null", new ArgumentNullException(path == null ? "path" : "node"));
}
// Will only be triggered if the caller isn't called by another Save().
if (encoding == null)
{
DebugBreakOrThrow("Figure out why encoding is null.", new ArgumentNullException("encoding"));
}
using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, 1024))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream, encoding))
{
// StreamWriter is a TextWriter, so we can pass it to HtmlNode.WriteContentTo(TextWriter).
// So node.WriteTo only saves the current node, which is only useful if the node has no children.
// node.WriteContentTo, only saves the current nodes children, therefore if the current node has a parent, we use the parent to save.
// this will include all siblings aswell :S
if (node.ParentNode != null)
{
node.ParentNode.WriteContentTo(streamWriter);
}
else if (node.HasChildNodes == false)
{
node.WriteTo(streamWriter);
}
else if (node.Name == HtmlNode.HtmlNodeTypeNameDocument)
{
node.WriteContentTo(streamWriter);
}
else
{
// TODO: Properly save parent-less node with children.
DebugBreakOrThrow("Properly save parent-less node with children. Inspect 'node'.", new InvalidOperationException("Don't know how to save the node, and it's children!"));
}
streamWriter.Flush();
}
}
}