Ejemplo n.º 1
0
        /// <summary>
        /// Saves a tree to a file.
        /// </summary>
        ///
        /// <exception cref="System.ArgumentNullException">Thrown if `root` is null.</exception>
        /// <exception cref="System.IO.IOException">Thrown if `overwrite` is false, and a tree called `name` already exists.</exception>
        ///
        /// <param name="name">The name to give the tree.</param>
        /// <param name="root">The root node of the tree.</param>
        /// <param name="overwrite">
        ///     If True, then if a tree called 'name' already exists, it is overwritten.
        ///     If False, then an IOException is thrown if a tree called 'name' already exists.
        /// </param>
        public static void saveTree(string name, Node root, bool overwrite = true)
        {
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }

            if (!overwrite && GameFiles.treeExists(name))
            {
                throw new IOException($"Unable to save tree {name} as it already exists, and overwrite is set to false.");
            }

            // Make sure the tree directory exists, then serialise `root` into a new tree file.
            GameFiles.ensureDirectories();
            using (var fs = new FileStream(GameFiles.makeTreePath(name), FileMode.Create))
            {
                using (var bw = new BinaryWriter(fs))
                {
                    /*
                     * Format:
                     *  [4 bytes, 'TREE']
                     *  [1 byte, file version]
                     *  [X bytes, serialised tree]
                     * */
                    bw.Write((char[])GameFiles._treeFileHeader.ToCharArray());
                    bw.Write((byte)GameFiles.treeFileVersion);
                    root.serialise(bw);
                }
            }
        }