Creating Torrents
Version 4 (Alan McGovern, 07/30/2009 12:14 AM) → Version 5/13 (Alan McGovern, 07/30/2009 12:28 AM)
h1. Creating Torrents
The first example shows you how to create a torrent synchronously. The second example builds on this and shows you how to create a torrent asynchronously, so that it does not block the main thread in your application.
*Example 1:*
<pre><code class="java">
// 'path' is the location of the file/folder which is going to be converted
// to a torrent. 'savePath' is where the .torrent file will be saved.
void CreateTorrent(string path, string savePath)
{
// The class used for creating the torrent
TorrentCreator c = new TorrentCreator();
// Add one tier which contains two trackers
List<string> tier = new List<string>();
tier.Add("http://www.example.com/announce");
tier.Add("http://backup.example.com/announce");
c.Announces.Add(tier);
c.Comment = "This is the comment";
c.CreatedBy = "Alan using " + VersionInfo.ClientVersion;
c.Publisher = "www.homepage.com";
// Set the torrent as private so it will not use DHT or peer exchange
// Generally you will not want to set this.
c.Private = true;
// Path can be either a directory *or* a file.
c.Path = path;
// Every time a piece has been hashed, this event will fire. It is an
// asynchronous event, so you have to handle threading yourself.
c.Hashed += delegate (object o, TorrentCreatorEventArgs e) {
Console.WriteLine("Current File is {0}% hashed", e.FileCompletion);
Console.WriteLine("Overall {0}% hashed", e.OverallCompletion);
Console.WriteLine("Total data to hash: {0}", e.OverallSize);
};
// Create the torrent file and save it to the specified path
c.Create(save_path);
}
</code></pre>
*Example 2:*
<pre><code class="java">
// 'path' is the location of the file/folder which is going to be converted
// to a torrent. 'savePath' is where the .torrent file will be saved.
void CreateTorrent(string path, string savePath)
{
// The class used for creating the torrent
TorrentCreator c = new TorrentCreator();
// Fill in the path, trackers as in Example 1
FillInStandardInformation(c);
// Create the torrent asynchronously
c.BeginCreate(c, TorrentCreated);
}
void TorrentCreated(IAsyncResult result)
{
TorrentCreator c = (TorrentCreator)result.AsyncState;
// If any errors occured while creating the torrent, they
// will be rethrown here.
try
{
// Open the destination file and use the EndCreate overload which
// writes the data directly to the Stream.
using (FileStream stream = File.OpenWrite(savePath))
c.EndCreate(result, stream);
}
catch (Exception ex)
{
Console.WriteLine("Error creating torrent: {0}", ex);
}
}
</code></pre> </code class="java"></pre>