Bruno Piovan

May 2009 - Posts

BEncoding and Torrent files with .Net

I wrote some code to handle bencoding/decoding in C#, the code is based on the specification. I created also a helper class to open/save torrent files and also compute its info_hash.

I wrote this project in C#, but the sample below is in visual basic. I don't think C# developers would have problems to understand it, but if you have any question just let me know.

Sub Main()
    'opens a torrent file and display its info_hash
    Dim torrentFile As BDictionary = Torrent.ParseTorrentFile("C:\Users\Bruno\Desktop\test.torrent")
    Console.Write("Existing torrent's info_hash: ")
    Console.WriteLine(Torrent.ComputeInfoHash(torrentFile).ToString)

    'creates a new torrent file
    Dim newtorrent As New BDictionary()
    newtorrent.Add("created by", "Bruno Piovan")

    'adds some integers
    newtorrent.Add("Ticks", Environment.TickCount)
    newtorrent.Add("Negative", Decimal.MinValue)

    'creates an info dictionary and adds it
    Dim info As New BDictionary
    newtorrent.Add("info", info)

    'generates some random bytes
    Dim sha As SHA512 = SHA512.Create
    Dim bytes() As Byte = sha.ComputeHash(Encoding.UTF8.GetBytes(Environment.TickCount.ToString))

    'adds the random bytes to the info dictionary
    info.Add("bytes", bytes)

    'adds a list
    Dim list As New BList
    For Each p As Process In Process.GetProcesses
        list.Add(p.ProcessName)
    Next
    info.Add("Processes", list)

    'computes the info_hash of the new torrent
    Console.Write("New torrent's info_hash:      ")
    Console.WriteLine(Torrent.ComputeInfoHash(newtorrent).ToString)

    'saves the torrent
    Torrent.SaveTorrent(newtorrent, "C:\Users\Bruno\Desktop\new-torrent.torrent")
End Sub

If you use this code, let me know if you find any bug or wrong implementation.

More Posts