Click here to Skip to main content
15,891,375 members
Articles / Programming Languages / C#

Named Binary Tag serialization

Rate me:
Please Sign up or sign in to vote.
4.93/5 (23 votes)
17 Feb 2015CC (ASA 3U)6 min read 67.4K   2.1K   51  
This article describes the file format NBT and shows how can be implemented in a real application to store data.
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using NBT.Tags;
using NBT.IO;

namespace NBT_Sample
{
    public partial class frmMain : Form
    {

        NBTFile nbtFile = new NBTFile();
        string filePath = Application.StartupPath + @"\test.nbt";

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            if (File.Exists(this.filePath) == true)
            {
                this.nbtFile.Load(this.filePath);
                this.ReloadList();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            this.nbtFile.Save(this.filePath);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.nbtFile.RootTag.Add(this.txtKey.Text, new TagString(this.txtValue.Text));
            this.ReloadList();
        }
        private void ReloadList()
        {
            this.lstItems.Items.Clear();
            foreach (KeyValuePair<string, Tag> item in this.nbtFile.RootTag)
            {
                if (item.Value.GetType() == typeof(TagString))
                {
                    ListBoxItem lstItem = new ListBoxItem();
                    lstItem.Text = ((TagString)item.Value).value;
                    lstItem.Tag = item.Key;
                    this.lstItems.Items.Add(lstItem);
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.lstItems.SelectedItems.Count > 0)
            { 
                ListBoxItem selectedItem = (ListBoxItem)this.lstItems.SelectedItem;
                this.nbtFile.RootTag.Remove((string)selectedItem.Tag);
                this.ReloadList();            
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License


Written By
Software Developer
Spain Spain
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions