29 Kasım 2009 Pazar

Simple Binary Encode (Bencode) library and torrent file encoder/decoder

Please download the source files from here...

As some of you might now that there is an encoding style called Bencode, which is capable of encoding four primitive data types, which are;


The popular p2p file sharing protocol BitTorrent also uses this encoding scheme in ".torrent" files which holds the meta data information about the published files. The protocol also uses bencode in the network layer to encode the p2p messages.

I want to share a simple Bencode library written by me in c# language. And also a ".torrent" file reader and generator. Sorry for the missing comments in the code but you're completely free to re-use and change it.

The usage of some core classes are as follows.

  1. BEncodedDocument _doc = new BEncodedDocument();
  2. _doc.LoadDocument(fileName);
These two lines of code simply creates a bencoded document object which can read a bencoded data from a file. You are free to extend this by adding the functionality of reading from another stream object like NetworkStream or FileStream.

BEncodedDocument class has an Elements propoerty which holds the bencoded elements in the file. The Elements property is a collection of one of the following objects referenced by IBinaryElement interface.

  1. BEncodedInt
  2. BEncodedString
  3. BEncodedList
  4. BEncodedDictionary
So, using the BEncodedDocument class you'll be able to load a bencoded document and traverse the data in an object oriented manner.

You may also use BEncodedDocument to read a ".torrent" file. The torrent file is simply a bencoded dictionary. The TorrentInfo class in the Inops.BEncode.TorrentFile project is able to read a ".torrent" file and decode the properties specific to that torrent. These properties represents all the torrent information necessary before starting to download it. Such as the tracker url, files, pieces, InfoHash, etc... Take a look at TorrentInfo class to further investigate these properties.

Hope this small work helps you...

Please download it from here and leave me a comment if you use it.