Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.IO;
- using System.Net;
- using System.Threading;
- namespace MyBBBot_v2
- {
- public class MessageReceivedEventArgs : EventArgs
- {
- public string Message;
- public ActionRequired ActionRequired;
- }
- public enum ActionRequired : int
- {
- MyBBCaptcha = 0,
- GoogleCaptcha = 1,
- SecurityQuestion = 2,
- }
- public class MyBB
- {
- /// <summary>
- /// The board URL
- /// </summary>
- public string URL { get; set; }
- /// <summary>
- /// The post key for the user.
- /// </summary>
- public string my_post_key { get; set; }
- /// <summary>
- /// The user's UID
- /// </summary>
- public string UID { get; set; }
- /// <summary>
- /// The board URL without the trailing slash.
- /// </summary>
- /// <param name="boardUrl"></param>
- public MyBB(string boardUrl)
- {
- this.URL = boardUrl;
- }
- private bool callbackComplete = false;
- private string callbackData = "";
- public event MessageReceivedEventHandler MessageReceived;
- public delegate void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs e);
- /// <summary>
- /// Logs a MyBB User in and stores their cookie
- /// </summary>
- /// <param name="user">Username</param>
- /// <param name="pass">Password</param>
- /// <returns>Returns true if the user has been successfully logged in.</returns>
- public bool Login(string user, string pass)
- {
- string data = Connections.postRequest(URL + "/member.php", string.Format("action=do_login&url=&username={0}&password={1}", user, pass), "");
- if (!data.Contains("invalid") && !data.Contains("verification"))
- {
- Regex mypostkey = new Regex(@"(?<=my_post_key = "").*?(?="")");
- my_post_key = mypostkey.Match(data).Value;
- Regex userID = new Regex("<a href=\".*\\?action=profile&uid=(.*?)\">");
- UID = userID.Match(data).Groups[1].Value;
- return true;
- }
- return false;
- }
- /// <summary>
- /// Gets the Cloudflare clearance cookie, bypassing Cloudflare's Under-Attack Mode
- /// </summary>
- /// <returns></returns>
- public bool GetCloudflareCookie()
- {
- string cloudflare = Connections.getRequest(URL, "");
- Regex answer = new Regex(@".value\s+=\s([\d\+\*\-]+)");
- Regex vc = new Regex(@"""([a-fA-F\d]{32})""");
- Match matchAnswer = answer.Match(cloudflare);
- Match matchVC = vc.Match(cloudflare);
- string vcstr = matchVC.Groups[1].Value;
- Uri url = new Uri(URL);
- string answerstr = matchAnswer.Groups[1].Value + "+" + url.Host.Length;
- MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
- sc.Language = "VBScript";
- int result = (int)sc.Eval(answerstr);
- string url2 = string.Format("http://{0}/cdn-cgi/l/chk_jschl?jschl_vc={1}&jschl_answer={2}", url.Host, vcstr, result.ToString());
- string good = Connections.getRequest(url2, "");
- if (good.Contains("Hello There, Guest!") || good.Contains("MyBB"))
- return true;
- else
- return false;
- }
- /// <summary>
- /// Reports a specific post ID
- /// </summary>
- /// <param name="postId">The post ID to report</param>
- /// <param name="reason">The reason to display</param>
- /// <returns>Returns true if successful.</returns>
- public bool ReportPost(string postId, string reason)
- {
- string data = Connections.postRequest(URL + "/report.php", string.Format("my_post_key={0}&action=do_report&pid={1}&reason={2}", my_post_key, postId, reason), URL + "/index.php");
- if (data.ToLower().Contains("thank you"))
- {
- return true;
- }
- return false;
- }
- /// <summary>
- /// Gives reputation to the specified user id.
- /// </summary>
- /// <param name="userID">The <see cref="UID"/> of the user.</param>
- /// <param name="amount">The amount of reputation, 0 for neutural.</param>
- /// <param name="repComment">The comment to display on the reputation.</param>
- /// <returns>Returns true if successful.</returns>
- public bool GiveReputation(string userID, int amount, string repComment)
- {
- string data = Connections.postRequest(URL + "/reputation.php", string.Format("my_post_key={0}&action=do_add&uid={1}&pid=0&rid=&reputation={2}&comments={3}", my_post_key, userID, amount, repComment), URL + "/index.php");
- if (data.ToLower().Contains("addded"))
- {
- return true;
- }
- return false;
- }
- /// <summary>
- /// Performs a shout in the MyBBShoutbox
- /// </summary>
- /// <param name="text">The text to send.</param>
- /// <returns>Returns true if successful.</returns>
- public bool ShoutMyShoutbox(string text)
- {
- string data = Connections.postRequest(URL + "/xmlhttp.php?action=add_shout", "shout_data=" + text, URL + "/index.php");
- if (data.ToLower().Contains("success!!"))
- {
- return true;
- }
- return false;
- }
- /// <summary>
- /// Creates a post on the specified thread ID
- /// </summary>
- /// <param name="threadID">The thread ID to post on.</param>
- /// <param name="subject">The subject of the post.</param>
- /// <param name="message">The message of the post.</param>
- /// <returns>Returns true if successful.</returns>
- public bool CreatePost(string threadID, string subject, string message)
- {
- string postHash = "";
- string lastPostID = "";
- string fromPage = "";
- string threadPage = Connections.getRequest(string.Format("{0}/showthread.php?tid={1}", URL, threadID), URL + "/index.php");
- Regex postHashR = new Regex(@"(?<=name=""posthash"" value="").*?(?="")");
- Regex lastPostIDR = new Regex(@"(?<=id=""lastpid"" value="").*?(?="")");
- Regex fromPageR = new Regex(@"(?<=name=""from_page"" value="").*?(?="")");
- postHash = postHashR.Match(threadPage).Value;
- lastPostID = lastPostIDR.Match(threadPage).Value;
- fromPage = fromPageR.Match(threadPage).Value;
- if (postHash != "" && lastPostID != "" && fromPage != "")
- {
- string data = Connections.postRequest(URL + "/newreply.php?ajax=1", string.Format("my_post_key={0}&subject={1}&action=do_newreply&posthash={2}"ed_ids=&lastpid={3}&from_page={4}&tid={5}&method=quickreply&postoptions%5Bsignature%5D=1&message={6}&previewpost=Preview%20Post", my_post_key, subject, postHashR, lastPostID, fromPage, threadID, message), URL + "/index.php");
- if (!data.Contains("The massage is too short.") && !data.Contains("The subject is too short."))
- {
- return true;
- }
- return false;
- }
- return false;
- }
- /// <summary>
- /// Creates a thread in the specified forum ID
- /// </summary>
- /// <param name="forumID">The forum ID to post the thread in.</param>
- /// <param name="subject">The subject of the thread.</param>
- /// <param name="newMessage">The message of the thread.</param>
- /// <returns>Returns true if successful.</returns>
- public bool CreateThread(string forumID, string subject, string newMessage)
- {
- string postHash = "";
- Regex postHashR = new Regex(@"(?<=name=""posthash"" value="").*?(?="")");
- string threadCreate = Connections.getRequest(URL + "/newthread.php?fid=" + forumID, URL + "/index.php");
- postHash = postHashR.Match(threadCreate).Value;
- Dictionary<string, object> Params = new Dictionary<string, object>();
- Params.Add("my_post_key", my_post_key);
- Params.Add("threadprefix", "0");
- Params.Add("subject", subject);
- Params.Add("icon", "-1");
- Params.Add("message_new", newMessage);
- Params.Add("message", newMessage);
- Params.Add("postoptions[signature]", "1");
- Params.Add("postoptions[subscriptionmethod", "");
- Params.Add("numpolloptions", "2");
- Params.Add("attachment", new FormUpload.FileParameter(null, ""));
- Params.Add("submit", "Post Thread");
- Params.Add("action", "do_newthread");
- Params.Add("posthash", postHash);
- Params.Add("attachmentaid", "");
- Params.Add("attachmentact", "");
- Params.Add("quoted_ids", "");
- Params.Add("tid", "");
- HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(URL + "/newthread.php?fid=" + forumID + "&processed=1", Connections.randUserAgent(), Params);
- StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
- string fullResponse = responseReader.ReadToEnd();
- webResponse.Close();
- return true;
- }
- public bool Register(string username, string password, string email, bool securityQuestions)
- {
- string failPage = Connections.postRequest(URL + "/member.php", "regcheck1=®check2=true&username=&password=&password2=&email=&email2=&referrername=&imagestring=&imagehash=&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=0&timezoneoffset=10&dstcorrection=2&language=&step=registration&action=do_register®submit=Submit+Registration%21", URL + "/member.php");
- Connections.cookieContainer.Add(new Cookie("coppadob", Connections.Rnd.Next(1, 25).ToString() + "-" + Connections.Rnd.Next(1, 12).ToString() + "-" + Connections.Rnd.Next(1940, 2000).ToString(), "/", new Uri(URL).Host));
- Regex mybbImageHash = new Regex(@"imagehash=.*?(?="")");
- Regex googleImageHash = new Regex(@"http://api.recaptcha.net/challenge\?.*?(?="")");
- Regex googleImageHash2 = new Regex(@"htt(p|ps)://www.google.com/recaptcha/api/challenge\?k=.*?(?="")");
- Regex regSecID = new Regex("regsecureq_id.*?=\"(.*?)\"");
- Regex regSecQuestion = new Regex("regsecureq\".*?>(.*?)</span>");
- Match matchMyBB = mybbImageHash.Match(failPage);
- Match matchGoogle = googleImageHash.Match(failPage);
- Match matchGoogle2 = googleImageHash2.Match(failPage);
- Match matchRegSecQuestion = regSecQuestion.Match(failPage);
- Match matchRegSecId = regSecID.Match(failPage);
- string regSecurityQuestion = "";
- string regSecurityQuestionID = "";
- if (securityQuestions)
- {
- regSecurityQuestion = matchRegSecQuestion.Groups[1].Value;
- regSecurityQuestionID = matchRegSecId.Groups[1].Value;
- }
- if (matchMyBB.Value != "" && matchMyBB.Success)
- {
- string imageLink = GetImageMyBB(matchMyBB.Value);
- MessageReceivedEventArgs e = new MessageReceivedEventArgs();
- e.ActionRequired = ActionRequired.MyBBCaptcha;
- e.Message = imageLink;
- MessageReceived(this, e);
- while (!callbackComplete)
- {
- Thread.Sleep(500);
- }
- string captcha = callbackData; // CHANGE IN REQUEST
- callbackComplete = false;
- callbackData = "";
- if (securityQuestions)
- {
- MessageReceivedEventArgs e2 = new MessageReceivedEventArgs();
- e2.ActionRequired = ActionRequired.SecurityQuestion;
- e2.Message = regSecurityQuestion;
- MessageReceived(this, e2);
- while (!callbackComplete)
- {
- Thread.Sleep(500);
- }
- }
- string realPage = "";
- string shit = matchMyBB.Value.Replace("imagehash=", "");
- if (!securityQuestions)
- {
- realPage = Connections.postRequest(URL + "/member.php", string.Format("regcheck1=®check2=true&username={0}&password={1}&password2={2}&email={3}&email2={4}&referrername=&imagestring={5}&imagehash={6}&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=0&timezoneoffset=10&dstcorrection=2&language=&step=registration&action=do_register®submit=Submit+Registration%21", username, password, password, email, email, captcha, matchMyBB.Value.Replace("imagehash=", "")), URL + "/member.php");
- }
- else
- {
- realPage = Connections.postRequest(URL + "/member.php", string.Format("regcheck1=®check2=true&username={0}&password={1}&password2={2}&email={3}&email2={4}&referrername=&imagestring={5}&imagehash={6}®secureans={7}®secureq_id={8}&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=0&timezoneoffset=10&dstcorrection=2&language=&step=registration&action=do_register®submit=Submit+Registration%21", username, password, password, email, email, captcha, matchMyBB.Value.Replace("imagehash=", ""), callbackData, regSecurityQuestionID), URL + "/member.php");
- }
- callbackComplete = false;
- callbackData = "";
- if (realPage.Contains("Thank you for registering") || realPage.Contains("You last visited:") || realPage.Contains(username))
- {
- return true;
- }
- return false;
- }
- else if (matchGoogle.Value != "" && matchGoogle.Success || matchGoogle2.Value != "" && matchGoogle2.Success)
- {
- string imageLink = "";
- string imageChallenge = "";
- if (matchGoogle.Value != "")
- {
- string[] data = GetImageGoogle(matchGoogle2.Value).Split('|');
- imageLink = data[0];
- imageChallenge = data[1];
- }
- else
- {
- string[] data = GetImageGoogle(matchGoogle2.Value).Split('|');
- imageLink = data[0];
- imageChallenge = data[1];
- }
- MessageReceivedEventArgs e = new MessageReceivedEventArgs();
- e.ActionRequired = ActionRequired.GoogleCaptcha;
- e.Message = imageLink;
- MessageReceived(this, e);
- while (!callbackComplete)
- {
- Thread.Sleep(500);
- }
- string captcha = callbackData;
- callbackComplete = false;
- callbackData = "";
- if (securityQuestions)
- {
- MessageReceivedEventArgs e2 = new MessageReceivedEventArgs();
- e2.ActionRequired = ActionRequired.SecurityQuestion;
- e2.Message = regSecurityQuestion;
- MessageReceived(this, e2);
- while (!callbackComplete)
- {
- Thread.Sleep(500);
- }
- }
- string realPage = "";
- if (!securityQuestions)
- {
- realPage = Connections.postRequest(URL + "/member.php", "regcheck1=®check2=true&username=" + username + "&password=" + password + "&password2=" + password + "&email=" + email + "&email2=" + email + "&referrername=&recaptcha_challenge_field=" + imageChallenge + "&recaptcha_response_field=" + captcha + "&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=2&timezoneoffset=-5&dstcorrection=2&language=&step=registration&action=do_register®submit=Submit+Registration%21", URL + "/member.php");
- }
- else
- {
- realPage = Connections.postRequest(URL + "/member.php", "regcheck1=®check2=true&username=" + username + "&password=" + password + "&password2=" + password + "&email=" + email + "&email2=" + email + "&referrername=&recaptcha_challenge_field=" + imageChallenge + "&recaptcha_response_field=" + captcha + "®secureans=" + callbackData + "®secureq_id=" + regSecurityQuestionID + "&allownotices=1&receivepms=1&pmnotice=1&subscriptionmethod=2&timezoneoffset=-5&dstcorrection=2&language=&step=registration&action=do_register®submit=Submit+Registration%21", URL + "/member.php");
- }
- callbackComplete = false;
- callbackData = "";
- if (realPage.Contains("Thank you for registering") || realPage.Contains("You last visited:"))
- {
- return true;
- }
- return false;
- }
- return false;
- }
- private string GetImageMyBB(string data)
- {
- return URL + "/captcha.php?action=regimage&" + data;
- }
- private string GetImageGoogle(string data)
- {
- Regex challRegex = new Regex("(?<=challenge : ').*?(?=')");
- Match challMatch = challRegex.Match(Connections.getRequest(data, ""));
- if (challMatch.Success)
- {
- string imageLink = "http://www.google.com/recaptcha/api/image?c=" + challMatch.Value + "|" + challMatch.Value;
- return imageLink;
- }
- return "";
- }
- public void CallBackAction(ActionRequired act, string answer)
- {
- callbackData = answer;
- callbackComplete = true;
- }
- /// <summary>
- /// Verifies the board account associated with the specified mailcatch.com email
- /// </summary>
- /// <param name="emailaddress">The mailcatch.com email address associated with the board account, @mailcatch.com</param>
- /// <returns></returns>
- public bool VerifyEmail(string emailaddress)
- {
- Regex mainPageRegex = new Regex("href=\"(\\?box=.*?&show.*?)\"");
- string mainPage = Connections.getRequest("http://mailcatch.com/en/temporary-inbox?box=" + emailaddress.Remove(emailaddress.IndexOf("@")), "");
- Match matchMainPage = mainPageRegex.Match(mainPage);
- if (matchMainPage.Success)
- {
- string link = "http://mailcatch.com/en/temporary-inbox" + matchMainPage.Groups[1].Value;
- //Regex activateUrlRegex = new Regex(string.Format("href=\"({0}/member.php\\?action=activate&uid=.*?)\"", URL));
- Regex activateUrlRegex = new Regex(string.Format("({0}/member.php\\?action=activate&uid=.*)", URL));
- string emailPage = Connections.getRequest(link, "");
- emailPage = emailPage.Replace("&", "&");
- Match matchActivate = activateUrlRegex.Match(emailPage);
- if (matchActivate.Success)
- {
- string activatePage = Connections.getRequest(matchActivate.Groups[1].Value, "");
- if (!activatePage.ToLower().Contains("account is already activated") || !activatePage.ToLower().Contains("hello there, guest"))
- return true;
- else
- return false;
- }
- }
- return false;
- }
- }
- class Connections
- {
- public static Random Rnd = new Random();
- public static CookieContainer cookieContainer { get; set; }
- public static byte[] ReceivedData { get; set; }
- public static string randUserAgent()
- {
- string[] MyStringArr = {
- //"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17",
- "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15",
- //"Mozilla/5.0 (Windows; U; Windows NT 6.1; x64; fr; rv:1.9.2.13) Gecko/20101203 Firebird/3.6.13",
- //"Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1",
- //"Mozilla/5.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1",
- //"Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2",
- //"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2",
- //"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.28) Gecko/20120410 Firefox/3.6.28 Lunascape/6.7.1.25446",
- //"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.8.1.9) Gecko/20071110 Sylera/3.0.20 SeaMonkey/1.1.6"
- };
- return MyStringArr[Rnd.Next(MyStringArr.Length)];
- }
- public MatchCollection RegexMatch(string Text, string Regexstring, RegexOptions Regexoption = RegexOptions.None)
- {
- System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(Regexstring, Regexoption);
- MatchCollection matches = r.Matches(Text.Trim());
- return matches;
- }
- public static string postRequest(string url, string data, string referer)
- {
- string postData = data;
- UTF8Encoding encoding = new UTF8Encoding();
- byte[] byteData = encoding.GetBytes(postData);
- HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create(url);
- postReq.Method = "POST";
- postReq.KeepAlive = true;
- postReq.Timeout = 8000;
- if (cookieContainer != null)
- {
- postReq.CookieContainer = cookieContainer;
- }
- else
- {
- cookieContainer = new CookieContainer();
- postReq.CookieContainer = cookieContainer;
- }
- postReq.ContentType = "application/x-www-form-urlencoded";
- postReq.Referer = referer;
- postReq.UserAgent = randUserAgent();
- postReq.ContentLength = byteData.Length;
- Stream postreqstream = postReq.GetRequestStream();
- postreqstream.Write(byteData, 0, byteData.Length);
- postreqstream.Close();
- HttpWebResponse postresponse = default(HttpWebResponse);
- try
- {
- postresponse = (HttpWebResponse)postReq.GetResponse();
- }
- catch (WebException ex)
- {
- postresponse = (HttpWebResponse)ex.Response;
- }
- foreach (Cookie cook in postresponse.Cookies)
- {
- postReq.CookieContainer.Add(cook);
- }
- cookieContainer = postReq.CookieContainer;
- StreamReader postreqreader = new StreamReader(postresponse.GetResponseStream());
- string thepage = postreqreader.ReadToEnd();
- return thepage;
- }
- public static string getRequest(string url, string referer)
- {
- HttpWebRequest postGet = (HttpWebRequest)WebRequest.Create(url);
- postGet.Timeout = 8000;
- postGet.Method = "GET";
- postGet.KeepAlive = true;
- if (cookieContainer != null)
- {
- postGet.CookieContainer = cookieContainer;
- }
- else
- {
- cookieContainer = new CookieContainer();
- postGet.CookieContainer = cookieContainer;
- }
- postGet.ContentType = "application/x-www-form-urlencoded";
- postGet.Referer = referer;
- postGet.UserAgent = randUserAgent();
- HttpWebResponse postGetresponse = null;
- try
- {
- postGetresponse = (HttpWebResponse)postGet.GetResponse();
- }
- catch (WebException ex)
- {
- postGetresponse = (HttpWebResponse)ex.Response;
- }
- StreamReader postGetreader = new StreamReader(postGetresponse.GetResponseStream());
- foreach (Cookie cook in postGetresponse.Cookies)
- {
- postGet.CookieContainer.Add(cook);
- }
- cookieContainer = postGet.CookieContainer;
- string thepage = postGetreader.ReadToEnd();
- return thepage;
- }
- public static string postRequestMultipart(string url, string data, string referer, string boundary)
- {
- string postData = data;
- UTF8Encoding encoding = new UTF8Encoding();
- byte[] byteData = encoding.GetBytes(postData);
- HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create(url);
- postReq.Method = "POST";
- postReq.KeepAlive = true;
- postReq.Timeout = 12000;
- if (cookieContainer != null)
- {
- postReq.CookieContainer = cookieContainer;
- }
- else
- {
- cookieContainer = new CookieContainer();
- postReq.CookieContainer = cookieContainer;
- }
- postReq.ContentType = "multipart/formdata; boundary=" + boundary;
- postReq.Referer = referer;
- postReq.UserAgent = randUserAgent();
- Stream postreqstream = postReq.GetRequestStream();
- using (StreamWriter streamWriter = new StreamWriter(postreqstream))
- {
- foreach (string str in data.Split(new string[] { "\r\n" }, StringSplitOptions.None))
- {
- streamWriter.WriteLine(str);
- }
- }
- postreqstream.Close();
- HttpWebResponse postresponse = default(HttpWebResponse);
- postresponse = (HttpWebResponse)postReq.GetResponse();
- foreach (Cookie cook in postresponse.Cookies)
- {
- postReq.CookieContainer.Add(cook);
- }
- cookieContainer = postReq.CookieContainer;
- StreamReader postreqreader = new StreamReader(postresponse.GetResponseStream());
- string thepage = postreqreader.ReadToEnd();
- return thepage;
- }
- public static string GetImage(string url)
- {
- HttpWebRequest postGet = (HttpWebRequest)WebRequest.Create(url);
- postGet.Timeout = 8000;
- postGet.Method = "GET";
- postGet.KeepAlive = true;
- if (cookieContainer != null)
- {
- postGet.CookieContainer = cookieContainer;
- }
- else
- {
- cookieContainer = new CookieContainer();
- postGet.CookieContainer = cookieContainer;
- }
- postGet.ContentType = "application/x-www-form-urlencoded";
- postGet.UserAgent = randUserAgent();
- HttpWebResponse postGetresponse = null;
- try
- {
- postGetresponse = (HttpWebResponse)postGet.GetResponse();
- }
- catch (WebException ex)
- {
- postGetresponse = (HttpWebResponse)ex.Response;
- }
- string file = "captcha_" + Environment.TickCount.ToString() + ".png";
- Byte[] lnByte = null;
- using (BinaryReader reader = new BinaryReader(postGetresponse.GetResponseStream()))
- {
- lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
- using (FileStream lxFS = new FileStream(file, FileMode.Create))
- {
- lxFS.Write(lnByte, 0, lnByte.Length);
- }
- }
- /*HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(url);
- lxRequest.CookieContainer = cookieContainer;
- lxRequest.Method = "GET";
- lxRequest.KeepAlive = true;
- // returned values are returned as a stream, then read into a string
- using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
- {
- using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream()))
- {
- lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10);
- using (FileStream lxFS = new FileStream(file, FileMode.Create))
- {
- lxFS.Write(lnByte, 0, lnByte.Length);
- }
- }
- }*/
- return file;
- }
- }
- // Implements multipart/form-data POST in C# http://www.ietf.org/rfc/rfc2388.txt
- // http://www.briangrinstead.com/blog/multipart-form-post-in-c
- public static class FormUpload
- {
- private static readonly Encoding encoding = Encoding.UTF8;
- public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
- {
- string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
- string contentType = "multipart/form-data; boundary=" + formDataBoundary;
- byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
- return PostForm(postUrl, userAgent, contentType, formData);
- }
- private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
- {
- HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
- if (request == null)
- {
- throw new NullReferenceException("request is not a http request");
- }
- // Set up the request properties.
- request.Method = "POST";
- request.ContentType = contentType;
- request.UserAgent = userAgent;
- request.CookieContainer = Connections.cookieContainer;
- request.ContentLength = formData.Length;
- // You could add authentication here as well if needed:
- // request.PreAuthenticate = true;
- // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
- // request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));
- // Send the form data to the request.
- using (Stream requestStream = request.GetRequestStream())
- {
- requestStream.Write(formData, 0, formData.Length);
- requestStream.Close();
- }
- return request.GetResponse() as HttpWebResponse;
- }
- private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
- {
- Stream formDataStream = new System.IO.MemoryStream();
- bool needsCLRF = false;
- foreach (var param in postParameters)
- {
- // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
- // Skip it on the first parameter, add it to subsequent parameters.
- if (needsCLRF)
- formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
- needsCLRF = true;
- if (param.Value is FileParameter)
- {
- FileParameter fileToUpload = (FileParameter)param.Value;
- // Add just the first part of this param, since we will write the file data directly to the Stream
- string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
- boundary,
- param.Key,
- fileToUpload.FileName ?? param.Key,
- fileToUpload.ContentType ?? "application/octet-stream");
- formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
- // Write the file data directly to the Stream, rather than serializing it to a string.
- //formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
- }
- else
- {
- string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
- boundary,
- param.Key,
- param.Value);
- formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
- }
- }
- // Add the end of the request. Start with a newline
- string footer = "\r\n--" + boundary + "--\r\n";
- formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
- // Dump the Stream into a byte[]
- formDataStream.Position = 0;
- byte[] formData = new byte[formDataStream.Length];
- formDataStream.Read(formData, 0, formData.Length);
- formDataStream.Close();
- return formData;
- }
- public class FileParameter
- {
- public byte[] File { get; set; }
- public string FileName { get; set; }
- public string ContentType { get; set; }
- public FileParameter(byte[] file) : this(file, null) { }
- public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
- public FileParameter(byte[] file, string filename, string contenttype)
- {
- File = file;
- FileName = filename;
- ContentType = contenttype;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement