Hopefully this helps someone avoid the trouble that I had getting this working. You may use this code however you like...just give credit where credit is due.
Code: Select all
using System.IO;
using System.Net;
//===========================================================
// Upload NZB provided by command line to SABnzbd queue
// 2011 - Bob Templeton - T3chDad™
//===========================================================
private void UploadNZB(string FileSpec, string Host, string Port, string apikey, string category)
{
// Create the boundary using unix EpochTime
DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
DateTime nowInUTC = DateTime.UtcNow;
string EpochTime = ((nowInUTC - baseTime).Ticks / 10000).ToString();
string boundary = "---------------------------" + EpochTime;
// Create the body for the request (POST)
string body = "--" + boundary + "\nContent-Disposition: form-data; name=\"name\"; filename=\"" + Path.GetFileName(FileSpec) + "\"\n";
// StreamReader to read the NZB File
TextReader tr = new StreamReader(FileSpec);
// Read the NZB and add to the request body
body += "Content-Type: application/x-nzb\n\n" + tr.ReadToEnd();
// Category
body += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"cat\"\n\n" + category;
// Priority
body += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"pp\"\n\n" + "-1";
// Scripts
body += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"script\"\n\n" + "Default";
body += "\n--" + boundary + "--\n\n";
// Build the URL
string URL = "http://" + Host + ":" + Port + "/sabnzbd/api?mode=addfile&name=" + Path.GetFileName(FileSpec) + "&apikey=" + apikey;
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(URL);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(body);
// Set the ContentType property of the WebRequest.
request.ContentType = "multipart/form-data; boundary=" + boundary;
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
//MessageBox.Show(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//MessageBox.Show(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}