/// <summary> /// Looks up a champion with the specified id. /// </summary> /// <param name="region">The region to check</param> /// <param name="championId">id of the champion to look up</param> /// <remarks>Version 1.2</remarks> /// <returns></returns> public Champion GetChampion(int championId) { Champion championCall = new Champion(); Champion staticChampionCall = new Champion(); DataContractJsonSerializer jSerializer = new DataContractJsonSerializer(typeof(Champion)); WebClient webClient = new WebClient(); try { championCall = (Champion)jSerializer.ReadObject(webClient.OpenRead(String.Format("https://{0}.api.pvp.net/api/lol/{0}/v1.2/champion/{1}?api_key={2}", _region, championId, _apiKey))); staticChampionCall = (Champion)jSerializer.ReadObject(webClient.OpenRead(string.Format("https://{0}.api.pvp.net/api/lol/static-data/{0}/v1.2/champion/{1}?champData=all&api_key={2}", _region, championId, _apiKey))); staticChampionCall.Active = championCall.Active; staticChampionCall.BotEnabled = championCall.BotEnabled; staticChampionCall.BotMmEnabled = championCall.BotMmEnabled; staticChampionCall.FreeToPlay = championCall.FreeToPlay; staticChampionCall.RankedPlayEnabled = championCall.RankedPlayEnabled; } catch (WebException e) { throw; } return staticChampionCall; }
public static object InvokeWebService(string url, string classname, string methodname, object[] args) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceProxy.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } }
public static void Download() { using (WebClient wcDownload = new WebClient()) { try { webRequest = (HttpWebRequest)WebRequest.Create(optionDownloadURL); webRequest.Credentials = CredentialCache.DefaultCredentials; webResponse = (HttpWebResponse)webRequest.GetResponse(); Int64 fileSize = webResponse.ContentLength; strResponse = wcDownload.OpenRead(optionDownloadURL); strLocal = new FileStream(optionDownloadPath, FileMode.Create, FileAccess.Write, FileShare.None); int bytesSize = 0; byte[] downBuffer = new byte[2048]; downloadForm.Refresh(); while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { strLocal.Write(downBuffer, 0, bytesSize); PercentProgress = Convert.ToInt32((strLocal.Length * 100) / fileSize); pBar.Value = PercentProgress; pLabel.Text = "Downloaded " + strLocal.Length + " out of " + fileSize + " (" + PercentProgress + "%)"; downloadForm.Refresh(); } } catch { } finally { webResponse.Close(); strResponse.Close(); strLocal.Close(); extractAndCleanup(); downloadForm.Hide(); } } }
public void UpdateFiles() { try { WriteLine("Local version: " + Start.m_Version); WebClient wc = new WebClient(); string versionstr; using(System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead(baseurl + "version.txt"))) { versionstr = sr.ReadLine(); } Version remoteversion = new Version(versionstr); WriteLine("Remote version: " + remoteversion); if(Start.m_Version < remoteversion) { foreach(string str in m_Files) { WriteLine("Updating: " + str); wc.DownloadFile(baseurl + str, str); } } wc.Dispose(); WriteLine("Update complete"); } catch(Exception e) { WriteLine("Update failed:"); WriteLine(e); } this.Button_Ok.Enabled = true; }
/// <summary> /// Used to perform the actual conversion of the input string /// </summary> /// <param name="InputString"></param> /// <returns></returns> public override string TranslateString(string InputString) { Console.WriteLine("Processing: " + InputString); string result = ""; using (WebClient client = new WebClient()) { using (Stream data = client.OpenRead(this.BuildRequestString(InputString))) { using (StreamReader reader = new StreamReader(data)) { string s = reader.ReadToEnd(); result = ExtractTranslatedString(s); reader.Close(); } data.Close(); } } return result; }
/// <summary> /// loads a xml from the web server /// </summary> /// <param name="_url">URL of the XML file</param> /// <returns>A XmlDocument object of the XML file</returns> public static XmlDocument LoadXml(string _url) { var xmlDoc = new XmlDocument(); try { while (Helper.pingForum("forum.mods.de", 10000) == false) { Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds..."); System.Threading.Thread.Sleep(15000); } xmlDoc.Load(_url); } catch (XmlException) { while (Helper.pingForum("forum.mods.de", 100000) == false) { Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds..."); System.Threading.Thread.Sleep(15000); } WebClient client = new WebClient(); ; Stream stream = client.OpenRead(_url); StreamReader reader = new StreamReader(stream); string content = reader.ReadToEnd(); content = RemoveTroublesomeCharacters(content); xmlDoc.LoadXml(content); } return xmlDoc; }
/// <summary> /// 获取微信分享signature参数的值 /// </summary> /// <returns></returns> private string gettict() { WebClient wc = new WebClient(); Stream myStream = wc.OpenRead("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa0e7d758fa3dbcf1&secret=fe230256d7889dc8f6c4c14669599598"); StreamReader sr = new StreamReader(myStream); String sLine = sr.ReadToEnd(); string access_token = sLine.Split(',')[0].Split(':')[1].Substring(1, sLine.Split(',')[0].Split(':')[1].Length - 2); wc.Dispose(); string url2 = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token); Stream myStream2 = wc.OpenRead(url2); StreamReader sr2 = new StreamReader(myStream2); String sLine2 = sr2.ReadToEnd(); string access_token1 = sLine2.Split(',')[2].Split(':')[1].Substring(1, sLine2.Split(',')[2].Split(':')[1].Length - 2); string string1 = string.Format("jsapi_ticket={0}&noncestr={1}×tamp={2}&url=http://www.zglsjy.com/item/dazhuanpan/index.aspx", access_token1, this.straa.Text, this.timestamp.Text); this.toke.Text = string1; // string string2 = "jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value"; return SHA1_Hash(string1); }
/// <summary> /// Gets the application with the given name from the server /// </summary> /// <param name="app"></param> public Application GetApplication(string name, string rootUrl) { CoreTools.Logger.DebugFormat("Getting online application info for \"{0}\" from {1}", name, rootUrl); // Make sure that the rootUrl ends with a '/' if (!rootUrl.EndsWith("/")) rootUrl += "/"; var application = new Application() { Name = name, Files = new List<string>(), ApplicationVersion = new Version(), WebRootUrl = rootUrl }; // Create a Http client to download data using (var httpClient = new WebClient()) { // Open filelist file on the server and store it in the object var versionRegex = new Regex(@"^[vV][0-9]*\.[0-9]*\.[0-9]*"); var filesContent = new StreamReader(httpClient.OpenRead(string.Format("{0}{1}/files.txt", rootUrl, name))); while (!filesContent.EndOfStream) { var line = filesContent.ReadLine(); // If line matches version format, parse version-number of current version if (versionRegex.IsMatch(line)) { var versions = line.Substring(1).Split(new string[] {"."}, StringSplitOptions.RemoveEmptyEntries); application.ApplicationVersion = new Version(Convert.ToInt32(versions[0]), Convert.ToInt32(versions[1]), Convert.ToInt32(versions[2]), 0); } else { application.Files.Add(line); } } // Get changelog var changelogReader = new StreamReader(httpClient.OpenRead(string.Format("{0}{1}/changelog.xml", rootUrl, name))); var xmlContent = changelogReader.ReadToEnd(); application.ChangeLog = System.Xml.Linq.XDocument.Parse(xmlContent); CoreTools.Logger.DebugFormat("Online application information for \"{0}\" loaded:", name); CoreTools.Logger.DebugFormat(" - Online version: {0}", application.ApplicationVersion); return application; } }
public ActionResult FacebookLogin(string code, string state, string returnUrl) { if (string.IsNullOrEmpty(code)) { // Redirect to Facebook Login var redirectUri = this.GetLoginAbsoluteUrl(); var facebookLoginUrl = "https://graph.facebook.com/oauth/authorize?client_id=" + this.facebookApiClientId + "&scope=&state=" + HttpUtility.UrlEncode(returnUrl) + "&redirect_uri=" + HttpUtility.UrlEncode(redirectUri); return this.Redirect(facebookLoginUrl); } var tokenUrl = string.Format( CultureInfo.InvariantCulture, "https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", this.facebookApiClientId, this.GetLoginAbsoluteUrl(), this.facebookApiClientSecret, code); var accessToken = string.Empty; try { using (var client = new WebClient()) { var receivedStream = client.OpenRead(tokenUrl); using (var tokenReader = new StreamReader(receivedStream)) { accessToken = tokenReader.ReadToEnd(); var userProfileUrl = new Uri(string.Format("{0}?{1}", FacebookApiProfileUrl, accessToken)); receivedStream = client.OpenRead(userProfileUrl); using (var profileReader = new StreamReader(receivedStream)) { receivedStream = client.OpenRead(userProfileUrl); var result = profileReader.ReadToEnd(); var userProfile = new JavaScriptSerializer().Deserialize<dynamic>(result); FormsAuthentication.SetAuthCookie(userProfile["name"], createPersistentCookie: true); return Redirect(string.IsNullOrEmpty(state) ? "~/" : HttpUtility.UrlDecode(state)); } } } } catch (Exception) { // TODO: Handle appropiate error. return Redirect("~/"); } }
/// <summary> /// Load just the header line /// </summary> /// <param name="URIDataFilename"></param> /// <param name="Headers"></param> public void LoadHeaderLine(string URIDataFilename, out string[] Headers) { string line = "[start of file]"; using (System.Net.WebClient webClient = new System.Net.WebClient()) { RequestCachePolicy policy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); webClient.CachePolicy = policy; try { using (System.IO.Stream stream = webClient.OpenRead(URIDataFilename)) { using (StreamReader reader = new StreamReader(stream)) { line = reader.ReadLine(); //read the header line Headers = ParseCSVLine(line); } } } catch (Exception ex) { Headers = null; } } }
public static IEnumerable <(string ico, string ds, string parentDS, string dsName)> UpdateListDS() { List <listBox> dsL = new List <listBox>(); string[] urls = new string[] { "https://www.mojedatovaschranka.cz/sds/datafile?format=xml&service=seznam_ds_ovm", "https://www.mojedatovaschranka.cz/sds/datafile?format=xml&service=seznam_ds_po", "https://www.mojedatovaschranka.cz/sds/datafile?format=xml&service=seznam_ds_pfo", "https://www.mojedatovaschranka.cz/sds/datafile?format=xml&service=seznam_ds_fo", }; var serializer = new XmlSerializer(typeof(list), "http://seznam.gov.cz/ovm/datafile/seznam_ds/v1"); var wc = new System.Net.WebClient(); foreach (var url in urls) { wc.Headers[HttpRequestHeader.AcceptEncoding] = "gzip"; var responseStream = new GZipStream(wc.OpenRead(url), CompressionMode.Decompress); var wcreader = new StreamReader(responseStream); var xmls = wcreader.ReadToEnd(); //var xmls = wc.DownloadString(url); using (TextReader reader = new StringReader(xmls)) { var dsFromXML = (list)serializer.Deserialize(reader); if (dsFromXML.box?.Count() > 0) { dsL.AddRange(dsFromXML.box); } } } return(dsL.Select( m => (m.ico, m.id, m.hierarchy?.masterId, m?.name?.tradeName) )); }
public static string GetLoginAddress(string nexusUri) { Net.WebClient webClient = new Net.WebClient(); // open connection to Nexus URL, then grab the headers (it has an empty body) IO.Stream strm = webClient.OpenRead(nexusUri); string passportUrls = webClient.ResponseHeaders["PassportURLs"]; strm.Close(); // get log in part of the http header we are looking at Regex.Regex regex = new Regex.Regex(@"DALogin=(?<loginURL>[^\,]+)", Regex.RegexOptions.Compiled); Regex.Match match = regex.Match(passportUrls); if (!match.Success) { throw new Exception(); } // put https on front if it isnt there string loginUrl = match.Groups["loginURL"].Value.ToLower(); if (!loginUrl.StartsWith("https://")) { loginUrl = "https://" + loginUrl; } // add port number after the host name int index = loginUrl.IndexOf("/", 9); loginUrl = loginUrl.Substring(0, index) + ":443" + loginUrl.Substring(index); return(loginUrl); }
//DONE //This method generates a list of operations from a web service description. Returns a list of the //webservice's operations on success, and null on failure. public string[] GetListOfOperations(string webServiceURL) { List<string> ListOfOperations = new List<string>(); WebClient webServiceClient = new WebClient(); Binding binding = new Binding(); try { Stream serviceStream = webServiceClient.OpenRead(webServiceURL + "?wsdl"); //This gets the WSDL file... ServiceDescription webServiceDescription = ServiceDescription.Read(serviceStream); //Get a list of operations from the web service description... binding = webServiceDescription.Bindings[0]; OperationBindingCollection operationCollection = binding.Operations; foreach (OperationBinding operation in operationCollection) { ListOfOperations.Add(operation.Name); } } catch (Exception ex) { throw ex; } return ListOfOperations.ToArray(); }
// GET: api/Bild2 public string Get(string artist) { string NyArtist = Plusa(artist); System.Net.WebClient wc = new System.Net.WebClient(); List <Bilder> B = new List <Bilder>(); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); string address = "https://www.last.fm/sv/music/" + NyArtist + "/+images"; doc.Load(wc.OpenRead(address)); HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//ul[@class='image-list']//img[@src]"); foreach (HtmlNode img in imgs) { if (img.Attributes["src"] == null) { continue; } HtmlAttribute src = img.Attributes["src"]; Bilder b = new Bilder(); b.kalla = src.Value; B.Add(b); } string sJson = JsonConvert.SerializeObject(B, Newtonsoft.Json.Formatting.Indented); return(sJson); }
public static void GetImageFromGravatar(string imageFileName, string email, int authorImageSize, FallBackService fallBack) { try { var baseUrl = String.Concat("http://www.gravatar.com/avatar/{0}?d=identicon&s=", authorImageSize, "&r=g"); if (fallBack == FallBackService.Identicon) baseUrl += "&d=identicon"; if (fallBack == FallBackService.MonsterId) baseUrl += "&d=monsterid"; if (fallBack == FallBackService.Wavatar) baseUrl += "&d=wavatar"; //hash the email address var emailHash = MD5.CalcMD5(email.ToLower()); //format our url to the Gravatar var imageUrl = String.Format(baseUrl, emailHash); var webClient = new WebClient { Proxy = WebRequest.DefaultWebProxy }; webClient.Proxy.Credentials = CredentialCache.DefaultCredentials; var imageStream = webClient.OpenRead(imageUrl); cache.CacheImage(imageFileName, imageStream); } catch (Exception ex) { //catch IO errors Trace.WriteLine(ex.Message); } }
//Image downloading stuff , also works for local files and GIF by RUNDEN static Image DownloadImage(string fromUrl) { try { if (fromUrl.ToLower().StartsWith("http") || !fromUrl.ToLower().EndsWith("gif")) { using (System.Net.WebClient webClient = new System.Net.WebClient()) { using (System.IO.Stream stream = webClient.OpenRead(fromUrl)) { return(Image.FromStream(stream)); } } } else { using (System.IO.FileStream fs = new System.IO.FileStream(fromUrl, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size int bytesRead; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, bytesRead); } ms.Position = 0; return(Image.FromStream(ms)); } } } catch { return(null); } }
private void load_splash(object sender, DoWorkEventArgs e) { if (Directory.Exists(path)) { } else { Directory.CreateDirectory(path); } ProcessStartInfo startup = new ProcessStartInfo(); startup.CreateNoWindow = true; startup.FileName = "adb.exe"; startup.Arguments = "start-server"; startup.RedirectStandardError = true; startup.RedirectStandardOutput = true; startup.UseShellExecute = false; var process = Process.Start(startup); process.WaitForExit(50000); WebClient client = new WebClient(); Stream stream = client.OpenRead("http://repo.itechy21.com/updatematerial.txt"); StreamReader reader = new StreamReader(stream); String content = reader.ReadLine(); Version a = new Version("0.0.0.1"); Version b = new Version(content); if (b > a) { Dispatcher.BeginInvoke(new Action(() => status.Content = "Update available!")); } else { Dispatcher.BeginInvoke(new Action(() => status.Content = "No Update available")); }; }
private void downloadData(Source source, string url, string bland) { WebClient wc = new WebClient(); Stream st = wc.OpenRead(url); Encoding enc = Encoding.GetEncoding("utf-8"); StreamReader sr = new StreamReader(st, enc); html = sr.ReadToEnd(); sr.Close(); st.Close(); //HTMLを解析する HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); //XPathで取得するNodeを指定 foreach (Field field in m_nodeName[source].Keys) { try { doc.DocumentNode.SelectNodes(m_nodeName[source][field]); var node = doc.DocumentNode.SelectSingleNode(m_nodeName[source][field]); m_marketData[bland][field] = node.InnerText; } catch (Exception err) { } } }
private void 网站公告推送_Load(object sender, EventArgs e) { System.Net.WebClient webClient = new System.Net.WebClient(); System.IO.Stream stream = webClient.OpenRead(@"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFd8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyLTJIdFVLSVFjWWoxLWNiNmh3YzkAAgSMPp9gAwQAjScA"); this.pictureBox1.Image = Image.FromStream(stream); stream.Dispose(); }
/*public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog) * { * float percent = 0; * try * { * System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); * System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); * long totalBytes = myrp.ContentLength; * if (prog != null) * { * prog.Maximum = (int)totalBytes; * } * System.IO.Stream st = myrp.GetResponseStream(); * System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); * long totalDownloadedByte = 0; * byte[] by = new byte[1024]; * int osize = st.Read(by, 0, (int)by.Length); * while (osize > 0) * { * totalDownloadedByte = osize + totalDownloadedByte; * System.Windows.Forms.Application.DoEvents(); * so.Write(by, 0, osize); * if (prog != null) * { * prog.Value = (int)totalDownloadedByte; * } * osize = st.Read(by, 0, (int)by.Length); * * percent = (float)totalDownloadedByte / (float)totalBytes * 100; * } * so.Close(); * st.Close(); * } * catch (System.Exception) * { * throw; * } * }*/ private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { string location = Application.StartupPath; // the URL to download the file from string sUrlToReadFileFrom = "http://cloud.soside.tk/mc1.8.zip"; // the path to write the file to int iLastIndex = sUrlToReadFileFrom.LastIndexOf('/'); string sDownloadFileName = sUrlToReadFileFrom.Substring(iLastIndex + 1, (sUrlToReadFileFrom.Length - iLastIndex - 1)); string textBoxDestinationFolder = "D:\\"; string sFilePathToWriteFileTo = textBoxDestinationFolder + "\\" + sDownloadFileName; // first, we need to get the exact size (in bytes) of the file we are downloading Uri url = new Uri(sUrlToReadFileFrom); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); // gets the size of the file in bytes Int64 iSize = response.ContentLength; // keeps track of the total bytes downloaded so we can update the progress bar Int64 iRunningByteTotal = 0; // use the webclient object to download the file using (System.Net.WebClient client = new System.Net.WebClient()) { // open the file at the remote URL for reading using (System.IO.Stream streamRemote = client.OpenRead(new Uri(sUrlToReadFileFrom))) { // using the FileStream object, we can write the downloaded bytes to the file system using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, FileMode.Create, FileAccess.Write, FileShare.None)) { // loop the stream and get the file into the byte buffer int iByteSize = 0; byte[] byteBuffer = new byte[iSize]; while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // write the bytes to the file system at the file path specified streamLocal.Write(byteBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; // calculate the progress out of a base "100" double dIndex = (double)(iRunningByteTotal); double dTotal = (double)byteBuffer.Length; double dProgressPercentage = (dIndex / dTotal); int iProgressPercentage = (int)(dProgressPercentage * 100); // update the progress bar backgroundWorker2.ReportProgress(iProgressPercentage); } // clean up the file stream streamLocal.Close(); } // close the connection to the remote server streamRemote.Close(); } } }
/// <summary> /// Downloads the specified web driver version. /// </summary> /// <param name="version">The version to download.</param> protected override void Update(string version) { using (var client = new WebClient()) using (var stream = client.OpenRead("http://chromedriver.storage.googleapis.com/" + version + "/chromedriver_win32.zip")) using (var archive = new ZipArchive(stream)) archive.ExtractToDirectory(Path.Combine(ParentPath, version)); }
// ** implementation // get closing prices for a given stock between 1/1/2008 and today // (uses Yahoo finance service) string GetPrices(string symbol) { var fmt = "http://ichart.finance.yahoo.com/table.csv?s={0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}&g=d"; // s: 0: stock symbol // a,b,c: 1,2,3: start month, day, year // d,e,f: 4,5,6: end month, day, year var t = DateTime.Today; var url = string.Format(fmt, symbol, 1, 1, 2008, t.Month, t.Day, t.Year); // get content var sb = new StringBuilder(); var wc = new WebClient(); using (var sr = new StreamReader(wc.OpenRead(url))) { // skip headers sr.ReadLine(); // skip first line (same date as the next!) sr.ReadLine(); // read each line for (var line = sr.ReadLine(); line != null; line = sr.ReadLine()) { // append date (field 0) and adjusted close price (field 6) var items = line.Split(','); sb.AppendFormat("{0}\t{1}\r", items[0], items[6]); } } // done var content = sb.ToString().Trim(); return content; }
public override void Draw(Graphics grfx, float time) { if (this.map == null) { GPSBox box = Gps.GetBox(); WebClient webClient = new WebClient(); string path = @"http://maps.googleapis.com/maps/api/staticmap?size="// TODO max heigth=640, max width=640 + GetBoundSize().Width + 'x' + GetBoundSize().Height + "&path=color:0x00000000|weight:5|" + (box.Position.Latitude - 0.00).ToString() + "," + (box.Position.Longitude - 0.00).ToString() + "|" + (box.Position.Latitude + 0.00 + box.Size.Latitude).ToString() + ',' + (box.Position.Longitude + 0.00 + box.Size.Longitude).ToString() + "+%20&sensor=false"; ////MessageBox.Show(path); // TODO use a variable instead of file try { this.map = new Bitmap(webClient.OpenRead(path)); } catch (WebException) { throw new WebException("Could not load google map"); } } grfx.DrawImage(this.map, PecentToPixels(ProjectSettings.GetSettings().TrackPostion)); }
private string getLatestVersion(string strUrl, out long result) { // Check if an update of the tool is available Cursor.Current = Cursors.WaitCursor; System.Net.WebClient wc = new System.Net.WebClient(); string myVersion; result = 0; try { wc.Credentials = System.Net.CredentialCache.DefaultCredentials; System.IO.Stream str; str = wc.OpenRead(strUrl); System.IO.StreamReader sr = new System.IO.StreamReader(str); myVersion = sr.ReadToEnd(); sr.Close(); long.TryParse(myVersion, out result); return(""); } catch (Exception ex) { return("ERROR: " + ex.Message.ToString()); } finally { Cursor.Current = Cursors.Default; } }
public Dictionary<int, float> GetItemPriceById(IEnumerable<int> eveId,bool sell=false) { var res = new Dictionary<int,float>(); //http://api.eve-central.com/api/marketstat?typeid=34&typeid=35®ionlimit=10000002 var url = new StringBuilder("http://api.eve-central.com/api/marketstat?"); foreach (var id in eveId) { url.Append("typeid=").Append(id).Append("&"); } url.Append("regionlimit=10000002"); using (var cli = new WebClient()) { var rdr = cli.OpenRead(url.ToString()); var ser = new XmlSerializer(typeof (evec_api)); if (rdr != null) { var objectRes = (evec_api)ser.Deserialize(rdr); foreach (var type in objectRes.marketstat) { res[type.id] = sell? type.sell.avg :type.buy.avg; } } } return res; }
// GET: api/Bilder public string Get(string artist) { System.Net.WebClient wc = new System.Net.WebClient(); List <Bilder> B = new List <Bilder>(); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); //string address = "https://www.bing.com/images/search?q=" + artist + "&qs=n&form=QBLH&scope=images&sp=-1&pq=" + artist + "&sc=8-6&sk=&cvid=B2B4DF8C73B444D398CA63F6317AC5D3"; //string address = "https://www.google.com/search?q=" + artist + "&tbm=isch&gws_rd=cr&ei=16E0WMGSKYmisAHmp6b4Ag"; string address = "http://images.search.yahoo.com/search/images;_ylt=AwrDQ3J1CF1ZqHIA0hH7w8QF?p=" + artist + "&fr=sfp&fr2=p%3As%2Cv%3Av%2Cm%3Apivot"; doc.Load(wc.OpenRead(address)); HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//img[@src]"); foreach (HtmlNode img in imgs) { if (img.Attributes["src"] == null) { continue; } HtmlAttribute src = img.Attributes["src"]; Bilder b = new Bilder(); b.kalla = src.Value; B.Add(b); } string sJson = JsonConvert.SerializeObject(B, Newtonsoft.Json.Formatting.Indented); return(sJson); }
/// <summary> /// Gets a web page from a url /// </summary> /// <param name="strUrl">URL of page to retrieve</param> /// <returns>String Page HTML</returns> public static string getPage(string strUrl) { string strTmp = ""; try { System.Net.WebClient objWebClient = new System.Net.WebClient(); System.IO.Stream MyStream = objWebClient.OpenRead(strUrl); System.IO.StreamReader srResponse = new System.IO.StreamReader(MyStream); strTmp = "" + srResponse.ReadToEnd(); return(strTmp); } catch (System.Net.WebException ex) { //Get full error page HttpWebResponse objResponse2; StreamReader srResponse2; objResponse2 = (System.Net.HttpWebResponse)ex.Response; srResponse2 = new StreamReader(objResponse2.GetResponseStream(), Encoding.ASCII); strTmp = srResponse2.ReadToEnd(); srResponse2.Close(); return(strTmp); } }
public static bool DownloadFromFtp(string fileName) { bool ret = true; var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string path = Path.Combine(dirName, fileName); try { var wc = new WebClient { Credentials = new NetworkCredential("solidk", "KSolid") }; var fileStream = new FileInfo(path).Create(); //string downloadPath = Path.Combine("ftp://194.84.146.5/ForDealers",fileName); string downloadPath = Path.Combine(Furniture.Helpers.FtpAccess.resultFtp+"ForDealers", fileName); var str = wc.OpenRead(downloadPath); const int bufferSize = 1024; var buffer = new byte[bufferSize]; int readCount = str.Read(buffer, 0, bufferSize); while (readCount > 0) { fileStream.Write(buffer, 0, readCount); readCount = str.Read(buffer, 0, bufferSize); } str.Close(); fileStream.Close(); wc.Dispose(); } catch { ret = false; } return ret; }
private WeatherInfo GetCurrentWeather() { XElement res; using (var client = new WebClient()) { using (var stream = client.OpenRead(WeatherClient.apiUrl)) { res = XElement.Load(stream); } } var current = res.Element("current_observation"); var forecasts = res.Element("forecast").Element("simpleforecast").Element("forecastdays").Elements("forecastday"); var todaysForecast = (from day in forecasts orderby day.Element("date").Element("epoch").Value select day).First(); var todaysForecastDate = todaysForecast.Element("date"); if (int.Parse(todaysForecastDate.Element("day").Value) != DateTime.Now.Day || int.Parse(todaysForecastDate.Element("month").Value) != DateTime.Now.Month) { throw new Exception("Wrong day / month for forecast"); } return new WeatherInfo() { CurrentFahrenheitTemperature = Double.Parse(current.Element("temp_f").Value), CurrentConditions = current.Element("weather").Value, ForecastConditions = todaysForecast.Element("conditions").Value, ChanceOfPrecipitation = int.Parse(todaysForecast.Element("pop").Value), HighFahrenheitTemperature = Double.Parse(todaysForecast.Element("high").Element("fahrenheit").Value), LowFahrenheitTemperature = Double.Parse(todaysForecast.Element("low").Element("fahrenheit").Value), }; }
public static bool IsAvailable(bool isVerboseOutput) { string resText = null; using (var wc = new WebClient()) { wc.Headers.Add("user-agent", UserAgent); const string checkServer = @"http://157.7.201.213/check.html"; if (isVerboseOutput) Console.WriteLine("trying \"GET\" " + checkServer + " ..."); for(var i = 1; i <= 5; i++) { try { var resData = wc.OpenRead(checkServer); using(var sr = new StreamReader(resData)) { resText = sr.ReadToEnd(); } break; } catch (WebException) { if (isVerboseOutput) Console.WriteLine(@"server is not responding"); } catch (Exception) { if (isVerboseOutput) Console.WriteLine(@"failed to an unknown error"); } } } return resText.Contains(@"<title>CHECK</title>"); }
public string getLatestVersion() { WebClient client = new WebClient(); Stream fs = client.OpenRead(SERVER_ADDRESS + VERSION_FILE_NAME); StreamReader sr = new StreamReader(fs); string version = null; string line = null; while (sr.Peek() >= 0) { line = sr.ReadLine(); int index = line.IndexOf("="); if (index > 0) { string key = line.Substring(0, index); if (key == "version") { version = line.Substring(index + 1); break; } } } sr.Close(); fs.Close(); return version; }
/// <summary> /// Devuelve un array de enteros de tamaño la capacidad del buffer. /// /// Es importante recordar que este método no debería plantear /// problemas de sincronismo mientras que no se cambiera el tamaño del /// buffer interno (es la única referencia a las propiedades del objeto). /// /// En esta clase en particular se establece una conexión a internet que puede fallar. /// Por ello si durante la conexión se lanza una WebException, se devuelve un valor null /// en vez de un array de enteros. /// /// Para más información sobre el CGI al que conecta consultar http://www.random.org/http.html /// </summary> protected override int[] GenerateBatch() { //string currentLine; string randomNumbersString; WebClient webclient = new WebClient(); try { Stream stream = webclient.OpenRead(String.Format("http://www.random.org/cgi-bin/randnum?num={0}&min={1}&max={2}&col=1", Configuration.EffectiveCapacity, Configuration.EffectiveMin, Configuration.EffectiveMax)); StreamReader streamReader = new StreamReader( stream ); randomNumbersString = streamReader.ReadToEnd( ); streamReader.Close(); stream.Close(); string[] randomNumbers = randomNumbersString.Split( '\n' ); int[] randomNumbersIntegers = new int[ randomNumbers.Length - 1 ]; // Convert the string array into an int array for ( int i = 0; i < randomNumbersIntegers.Length; i++ ) { randomNumbersIntegers[i] = int.Parse( randomNumbers[i] ); } return randomNumbersIntegers; } catch (WebException /*e*/) { return null; } }
public string DropCall() { //If api key provided if (!string.IsNullOrEmpty(api_key)) { //Creating Dynamic URL string url = "http://api.speek.com/calls/dropCall/?"; url += "api_key=" + api_key; if (!string.IsNullOrEmpty(format.Trim())) { url += "&format=" + format; } if (!string.IsNullOrEmpty(call_id.Trim())) { url += "&call_id=" + call_id; } WebClient client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); try { Stream data = client.OpenRead(url); StreamReader reader = new StreamReader(data); string s = reader.ReadToEnd(); return s; } catch (Exception ex) { Console.WriteLine(ex.Message); //return "Error"; } } return "API Key Not Provided"; }
public string GetCurrentSetting() { string[] existingLines = File.ReadAllLines(@"C:\Windows\System32\drivers\etc\hosts"); string[] expectedLines = new string[0]; try { using (WebClient client = new WebClient()) { using (Stream stream = client.OpenRead(@"http://winhelp2002.mvps.org/hosts.txt")) { using (StreamReader reader = new StreamReader(stream)) { expectedLines = reader.ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); } } } } catch (Exception) { return "disabled - error"; } if (!expectedLines.Except(existingLines).Any()) { return "enabled"; } return "disabled"; }
public void TestMethod1() { var web = new WebClient(); var stream = web.OpenRead("http://" + Environment.GetEnvironmentVariable("APPNAME")); var result = new StreamReader(stream).ReadToEnd(); Assert.IsTrue(result.Contains("ASP.NET MVC Website") && result.Contains("Home")); }
public List<ListedOption> GetContractList() { string contents = string.Empty; var contractList = new List<ListedOption>(); string uri = ListedProductsDownloadUrl.Replace("{ReportDate}", "20160511"); uri = @"http://www.optionseducation.org/quotes.html?quote=SPX"; WebClient wClient = new WebClient(); wClient.DownloadDataCompleted += wClient_DownloadDataCompleted; Stream stream = wClient.OpenRead(uri); StreamReader sr = new StreamReader(stream); { while (!sr.EndOfStream) { var readLine = sr.ReadLine(); if (!string.IsNullOrEmpty(readLine)) { var line = readLine; //ListedOption o = new ListedOption //{ // OptionSymbol = line[0], // UnderlyingSymbol = line[1], // SymbolName = line[2], // OnnProductType = line[3], // PostionLimit = line[4], // Exchanges = line[5] //}; //contractList.Add(o); } } sr.Close(); } return contractList; }
private void download(string link, string path) { Uri url = new Uri(link); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); Int64 iSize = response.ContentLength; using (System.Net.WebClient client = new System.Net.WebClient()) { using (System.IO.Stream streamRemote = client.OpenRead(new Uri(link))) { using (Stream streamLocal = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { int iByteSize = 0; byte[] byteBuffer = new byte[8192]; while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { streamLocal.Write(byteBuffer, 0, iByteSize); } streamLocal.Close(); } streamRemote.Close(); } } }
public static void LoadRegex() { Task.Factory.StartNew(() => { try { using (var notify = NotifyStorage.NotifyManually("img.azyobuzi.net: 正規表現を取得しています...")) using (var wc = new WebClient()) using (var reader = JsonReaderWriterFactory.CreateJsonReader( wc.OpenRead("http://img.azyobuzi.net/api/regex.json"), XmlDictionaryReaderQuotas.Max)) { Resolver.RegexArray = XElement.Load(reader).Elements() .Select(xe => new Regex(xe.Element("regex").Value, RegexOptions.IgnoreCase)) .ToArray(); } } catch (Exception ex) { ExceptionStorage.Register( ex, ExceptionCategory.PluginError, "img.azyobuzi.net: 正規表現の読み込みに失敗しました。", LoadRegex ); } }); }
private void Start(object o) { try { Station station = (Station)o; WebClient client = new WebClient(); Stream openRead = client.OpenRead(String.Format(ConfigurationService.ShoutcastPlaylistURL, station.ID)); StreamReader reader = new StreamReader(openRead); bool foundIP = false; while (!reader.EndOfStream && !foundIP) { string line = reader.ReadLine(); Regex regex = new Regex(@"(?<ip>[0-9]+.[0-9]+.[0-9]+.[0-9]+):(?<port>[0-9]+)"); Match match = regex.Match(line); if (match.Success) { String IP = match.Groups["ip"].Value; int port = Int32.Parse(match.Groups["port"].Value); IPAddress parsedIPAddress = IPAddress.Parse(IP); if (parsedIPAddress != null) { IPEndPoint endPoint = new IPEndPoint(parsedIPAddress, port); PortProber prober = new PortProber(endPoint); station.IsAlive = prober.ProbeMachine(); foundIP = true; } } } } catch (Exception e) { } }
public String ScrapeAnimeFreakTV() { int count = 0; String result = ""; WebClient client = new WebClient(); StreamReader reader = new StreamReader(client.OpenRead(url.Text)); string lines = reader.ReadToEnd(); string[] regex = lines.Split("'".ToCharArray()[0]); foreach (string str in regex) { String uri = Uri.UnescapeDataString(str); if (IsValidURL(uri) && uri.Contains(".mp4") && uri.Contains("af")) { Console.WriteLine(Uri.UnescapeDataString(str)); result = uri; } } return result; }
public static object UploadData(string url, string @namespace, string classname, string methodname, object[] args, ArrayList al) { try { System.Net.WebClient wc = new System.Net.WebClient(); //System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.IO.Stream stream = wc.OpenRead(url); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, string.Empty, string.Empty); //将sd描述导入到sdi中 System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); ParameterModifier[] paramsModifer = new ParameterModifier[1]; paramsModifer[0] = new ParameterModifier(args.Length); //paramsModifer[0][7] = true; object result = t.InvokeMember(methodname, BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args, paramsModifer, null, null); //al.Add(args[7]); return(result); } catch (Exception ex) { WriteLog(ex.Message, EXCEPTION_LOG_TITLE); return(null); } }
/// <summary> 根据参数执行WebService </summary> public static object InvokeWebService(string url, string classname, string methodname, object[] args) { try { string _namespace = "WebService"; if (string.IsNullOrEmpty(classname)) { classname = GetClassName(url); } //获取服务描述语言(WSDL) Net.WebClient wc = new Net.WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); //【1】 Web.Services.Description.ServiceDescription sd = Web.Services.Description.ServiceDescription.Read(stream); //【2】 Web.Services.Description.ServiceDescriptionImporter sdi = new Web.Services.Description.ServiceDescriptionImporter(); //【3】 sdi.AddServiceDescription(sd, "", ""); CodeDom.CodeNamespace cn = new CodeDom.CodeNamespace(_namespace); //【4】 //生成客户端代理类代码 CodeDom.CodeCompileUnit ccu = new CodeDom.CodeCompileUnit(); //【5】 ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //CSharpCodeProvider csc = new CSharpCodeProvider();//【6】 CodeDom.Compiler.CodeDomProvider csc = CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); //ICodeCompiler icc = csc.CreateCompiler();//【7】 //设定编译器的参数 CodeDom.Compiler.CompilerParameters cplist = new CodeDom.Compiler.CompilerParameters();//【8】 cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);//【9】 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new StringBuilder(); foreach (CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(_namespace + "." + classname, true, true); object bj = Activator.CreateInstance(t); //【10】 System.Reflection.MethodInfo mi = t.GetMethod(methodname); //【11】 return(mi.Invoke(bj, args)); } catch (System.Exception ex) { Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace); //MessageManager.ShowErrorMsg(ex.Message.ToString(), "test"); return(null); } }
public static Avatar GetAvatar(string id) { string httpHeaderLine = null; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create($@"https://Hazeron.com/EmpireStandings/p{id}.php"); request.Timeout = 5000; request.Method = "GET"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream receiveStream = response.GetResponseStream()) { StreamReader sr = new StreamReader(receiveStream, Encoding.UTF8); string httpLine; while ((httpLine = sr.ReadLine()) != null) { if (httpLine.Contains("Shores of Hazeron")) { httpHeaderLine = httpLine; break; } } } } } catch (System.Net.WebException) { // Blackhole. } if (httpHeaderLine == null) { // If the website wasn't found, check if the website is down or not. try { using (System.Net.WebClient client = new System.Net.WebClient()) { using (var stream = client.OpenRead(@"https://hazeron.com/status.php")) { // The website is not down, so the avatar really doesn't exist. throw new HazeronAvatarNotFoundException(id); } } } catch (System.Net.WebException ex) { // The website is down, so the avatar might still exist. throw new HazeronWebsiteNotFoundException(ex); } } const string start = "<title>Shores of Hazeron - "; const string end = "</title>"; int startIndex = httpHeaderLine.IndexOf(start) + start.Length; int endIndex = httpHeaderLine.IndexOf(end) - startIndex; string name = httpHeaderLine.Substring(startIndex, endIndex); return(new Avatar(name, id)); }
public void RSPEC_WebClient(string address, Uri uriAddress, byte[] data, NameValueCollection values) { System.Net.WebClient webclient = new System.Net.WebClient(); // All of the following are Questionable although there may be false positives if the URI scheme is "ftp" or "file" //webclient.Download * (...); // Any method starting with "Download" webclient.DownloadData(address); // Noncompliant webclient.DownloadDataAsync(uriAddress, new object()); // Noncompliant webclient.DownloadDataTaskAsync(uriAddress); // Noncompliant webclient.DownloadFile(address, "filename"); // Noncompliant webclient.DownloadFileAsync(uriAddress, "filename"); // Noncompliant webclient.DownloadFileTaskAsync(address, "filename"); // Noncompliant webclient.DownloadString(uriAddress); // Noncompliant webclient.DownloadStringAsync(uriAddress, new object()); // Noncompliant webclient.DownloadStringTaskAsync(address); // Noncompliant // Should not raise for events webclient.DownloadDataCompleted += Webclient_DownloadDataCompleted; webclient.DownloadFileCompleted += Webclient_DownloadFileCompleted; webclient.DownloadProgressChanged -= Webclient_DownloadProgressChanged; webclient.DownloadStringCompleted -= Webclient_DownloadStringCompleted; //webclient.Open * (...); // Any method starting with "Open" webclient.OpenRead(address); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ {{Make sure that this http request is sent safely.}} webclient.OpenReadAsync(uriAddress, new object()); // Noncompliant webclient.OpenReadTaskAsync(address); // Noncompliant webclient.OpenWrite(address); // Noncompliant webclient.OpenWriteAsync(uriAddress, "STOR", new object()); // Noncompliant webclient.OpenWriteTaskAsync(address, "POST"); // Noncompliant webclient.OpenReadCompleted += Webclient_OpenReadCompleted; webclient.OpenWriteCompleted += Webclient_OpenWriteCompleted; //webclient.Upload * (...); // Any method starting with "Upload" webclient.UploadData(address, data); // Noncompliant webclient.UploadDataAsync(uriAddress, "STOR", data); // Noncompliant webclient.UploadDataTaskAsync(address, "POST", data); // Noncompliant webclient.UploadFile(address, "filename"); // Noncompliant webclient.UploadFileAsync(uriAddress, "filename"); // Noncompliant webclient.UploadFileTaskAsync(uriAddress, "POST", "filename"); // Noncompliant webclient.UploadString(uriAddress, "data"); // Noncompliant webclient.UploadStringAsync(uriAddress, "data"); // Noncompliant webclient.UploadStringTaskAsync(uriAddress, "data"); // Noncompliant webclient.UploadValues(address, values); // Noncompliant webclient.UploadValuesAsync(uriAddress, values); // Noncompliant webclient.UploadValuesTaskAsync(address, "POST", values); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Should not raise for events webclient.UploadDataCompleted += Webclient_UploadDataCompleted; webclient.UploadFileCompleted += Webclient_UploadFileCompleted; webclient.UploadProgressChanged -= Webclient_UploadProgressChanged; webclient.UploadStringCompleted -= Webclient_UploadStringCompleted; webclient.UploadValuesCompleted -= Webclient_UploadValuesCompleted; }
public string GetIPFromDomainName(string domain_name) { System.Net.WebClient myWebClient = new System.Net.WebClient(); System.IO.Stream myStream = myWebClient.OpenRead(domain_name); System.IO.StreamReader myStreamReader = new System.IO.StreamReader(myStream); string ip = myStreamReader.ReadToEnd(); return(ip); }
public static object WebserviceInvoke(string p_strUrl, string p_strNameSpace, string p_strClassName, string p_strMethodName, object[] p_objArgs) { object oReturnValue = null; try { if (p_strNameSpace == "") { p_strNameSpace = "EnterpriseServerBase.WebService.DynamicWebCalling"; } if (p_strClassName == "") { p_strClassName = WebServiceHelper.GetWsClassName(p_strUrl); } System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(p_strUrl + "?wsdl"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(p_strNameSpace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(p_strNameSpace + "." + p_strClassName, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(p_strMethodName); oReturnValue = mi.Invoke(obj, p_objArgs); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } return(oReturnValue); }
protected void Button1_Click(object sender, EventArgs e) { System.Net.WebClient client = new System.Net.WebClient(); Stream d; StreamReader r; string line; string linen; int cuenta = 0; bool encontrado = false; //d = client.OpenRead("http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarCuadroAnalitico&idCuadro=CA113§or=6&presentacionCompacta=true&locale=es"); // Accede a la pagina que quieres buscar11. d = client.OpenRead("http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarCuadroAnalitico&idCuadro=CA113§or=6&locale=es"); // Accede a la pagina que quieres buscar11. r = new StreamReader(d); // lee la informacion o contenido de la web line = r.ReadLine(); // recorre linea x linea la web while (line != null) // mientras exista contenido { line = r.ReadLine(); if (line != null) { linen = line.Replace(" ", ""); if ((linen == "Euro3/") || (encontrado)) { cuenta++; encontrado = true; } if (cuenta == 4) { Label1.Text = linen; break; } } } d.Close(); try { if (Label1.Text != "") { int?res = -1; set_insertaTipoCambio_EUROTableAdapter setTipoCAmbioEuro = new set_insertaTipoCambio_EUROTableAdapter(); setTipoCAmbioEuro.GetData(System.Convert.ToDouble(Label1.Text), ref res); if (res == 1) { Label1.Text = "OK"; } else { Label1.Text = "ERROR"; } } } catch (Exception ex) { Label1.Text = "ERROR CATCH"; } }
public Image DownloadImage(string url) { using (System.Net.WebClient webClient = new System.Net.WebClient()) { using (Stream stream = webClient.OpenRead(url)) { return(Image.FromStream(stream)); } } }
public static Bitmap GetBitMap(string filename) { using (var client = new System.Net.WebClient()) { var stream = client.OpenRead(filename); Bitmap bitmap; bitmap = new Bitmap(stream); return(bitmap); } }
public void DownloadGame() { System.Net.WebClient client = new System.Net.WebClient(); client.OpenRead("https://dl.yanderesimulator.com/latest.zip"); Int64 bytes_total = Convert.ToInt64(client.ResponseHeaders["Content-Length"]); b = (int)(bytes_total / 1000000) + 1; client.DownloadFile("https://dl.yanderesimulator.com/latest.zip", path + "/" + url.Name); ZipFile.ExtractToDirectory(path + "/" + url.Name, path); }
/// <summary> /// Loads content of the resource from WebDAV server. /// </summary> /// <returns>Stream to read resource content.</returns> public Stream GetReadStream() { NetworkCredential credentials = (NetworkCredential)this._credentials; string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(credentials.UserName + ":" + credentials.Password)); System.Net.WebClient webClient = new System.Net.WebClient(); webClient.Credentials = credentials; webClient.Headers.Add("Authorization", auth); return(webClient.OpenRead(this._href)); }
/// <summary> /// Get the file with progress bar updates /// /// Inspired by: /// http://www.devtoolshed.com/content/c-download-file-progress-bar /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundWorkerBonjourDownload_DoWork(object sender, DoWorkEventArgs e) { Uri url = new Uri((is64bit) ? downloadUrl64Bit : downloadUrl32Bit); downloadTarget = Path.GetTempPath() + "BonjourSetup.exe"; // Get filesize System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); // gets the size of the file in bytes Int64 iSize = response.ContentLength; // keeps track of the total bytes downloaded so we can update the progress Int64 iRunningByteTotal = 0; // use the webclient object to download the file using (System.Net.WebClient client = new System.Net.WebClient()) { // open the file at the remote URL for reading using (System.IO.Stream streamRemote = client.OpenRead(url)) { // using the FileStream object, we can write the downloaded bytes to the file system using (Stream streamLocal = new FileStream(downloadTarget, FileMode.Create, FileAccess.Write, FileShare.None)) { // loop the stream and get the file into the byte buffer int iByteSize = 0; byte[] byteBuffer = new byte[iSize]; while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // write the bytes to the file system at the file path specified streamLocal.Write(byteBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; // calculate the progress out of a base "100" double dIndex = (double)(iRunningByteTotal); double dTotal = (double)byteBuffer.Length; double dProgressPercentage = (dIndex / dTotal); int iProgressPercentage = (int)(dProgressPercentage * 100); // update the progress bar backgroundWorkerBonjourDownload.ReportProgress(iProgressPercentage); } // clean up the file stream streamLocal.Close(); } // close the connection to the remote server streamRemote.Close(); } } }
private static void VisitPosts(Dictionary <string, bool> posts, System.Net.WebClient client, string baseUrl, string targetDir, ICollection <string> alreadyRead) { string[] postUrls = posts.Where(kvp => !kvp.Value).Select(kvp => kvp.Key).ToArray(); Console.WriteLine($"{postUrls.Length} items."); foreach (var item in postUrls) { using (var stream = client.OpenRead(item)) { try { var doc = new HtmlDocument(); doc.Load(stream); var n = doc.DocumentNode.SelectSingleNode("//img[@id='image']"); if (n == null) { continue; //rarely an swf file or something. } var target = n.GetAttributeValue("src", ""); if (string.IsNullOrEmpty(target)) { continue; } //sometimes they have complete urls instead of relative ones... if (!CheckUri(target)) { target = CombineUri(baseUrl, target); } var fileName = Path.GetFileName(target).Trim('_'); if (alreadyRead.Contains(fileName)) //don't re-download { FileDone(posts, item); continue; } fileName = Path.Combine(targetDir, fileName); if (File.Exists(fileName)) { FileDone(posts, item); continue; } client.DownloadFile(target, fileName); //Console.WriteLine(fileName); FileDone(posts, item); Thread.Sleep(123); //don't overload server. } catch (Exception ex) { Console.WriteLine(); Console.WriteLine($"Failed with {item}:\r{ex.Message}"); } } } }
//data loader object GetObjectManagerService(string WebServer, string WebServerU, string WebServerP) { if (string.IsNullOrEmpty(WebServer)) { throw new Exception("Invalid web server address!"); } //store all instances of service class as each instance is a separate dll and loaded each time into memory string hash = Webhash(WebServer, WebServerU, WebServerP); if (WebServices.ContainsKey(hash)) { return(WebServices[hash]); } ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); using (System.Net.WebClient client = new System.Net.WebClient()) { CorrectWebAddress(ref WebServer); System.IO.Stream stream = client.OpenRead(WebServer + ObjectManagerServiceName + ".asmx?wsdl"); importer.ProtocolName = "Soap12"; ServiceDescription description = ServiceDescription.Read(stream); importer.AddServiceDescription(description, null, null); importer.Style = ServiceDescriptionImportStyle.Client; } importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties; CodeNamespace nmspace = new CodeNamespace(); NameSpaceCounter++; CodeCompileUnit CompileUnit = new CodeCompileUnit(); CompileUnit.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, CompileUnit); if (warning == 0) { string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" }; CompilerParameters parms = new CompilerParameters(assemblyReferences); CompilerResults results; using (CodeDomProvider DomProvider = CodeDomProvider.CreateProvider("CSharp")) { results = DomProvider.CompileAssemblyFromDom(parms, CompileUnit); } object wsvcClass = results.CompiledAssembly.CreateInstance(ObjectManagerServiceName); WebServices[hash] = wsvcClass; return(wsvcClass); } throw new Exception(message: "Failed to connect to web servie. Check web server exists."); }
/// <summary> ///GET 请求 ///url 发送请求的链接,返回请求值 /// </summary> public static string GetReturn(string uriStr, string postData) { System.Net.WebClient clinet = new System.Net.WebClient(); //打开URL,GET参数以URL后缀的方式就可以传递过去。 System.IO.Stream stream = clinet.OpenRead(uriStr + postData); //把从HTTP中返回的流读为string System.IO.StreamReader reader = new System.IO.StreamReader(stream); string result = reader.ReadToEnd(); return(result); }
//根据网络获取一张图片 public static System.Drawing.Bitmap GetNetImage(string url) { System.Drawing.Image Logo = null; System.Net.WebClient wb = new System.Net.WebClient(); Stream stream = wb.OpenRead(url); //网址自己改吧 Logo = System.Drawing.Image.FromStream(stream); stream.Dispose(); stream.Close(); wb.Dispose(); return((System.Drawing.Bitmap)Logo); }
void GetCountry(string IP) { WebClient wc = new System.Net.WebClient(); Stream stream = wc.OpenRead("http://geoip.nekudo.com/api/" + IP); StreamReader reader = new StreamReader(stream); Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine()); Console.WriteLine((string)jObject["ip"][0]["country"]); stream.Close(); }
static void Example4() { System.Net.WebClient wc = new System.Net.WebClient(); wc.Proxy = null; System.IO.Stream stream = wc.OpenRead("http://zmp3-photo-td.zadn.vn/thumb/240_240/covers/9/a/9a156337c55bdc47e1f65963c24077df_1499654363.jpg"); using (System.Drawing.Image image = Image.FromStream(stream)) { image.Save("e4.png"); } System.Diagnostics.Process.Start("e4.png"); }
private void StartWorkerDownload(string downUrl, string destination, BackgroundWorker worker) { // first, we need to get the exact size (in bytes) of the file we are downloading Uri url = new Uri(downUrl); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); // gets the size of the file in bytes Int64 iSize = response.ContentLength; // keeps track of the total bytes downloaded so we can update the progress bar Int64 iRunningByteTotal = 0; // use the webclient object to download the file using (System.Net.WebClient client = new System.Net.WebClient()) { // open the file at the remote URL for reading using (System.IO.Stream streamRemote = client.OpenRead(new Uri(downUrl))) { // using the FileStream object, we can write the downloaded bytes to the file system using (Stream streamLocal = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None)) { // loop the stream and get the file into the byte buffer int iByteSize = 0; byte[] byteBuffer = new byte[iSize]; while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // write the bytes to the file system at the file path specified streamLocal.Write(byteBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; // calculate the progress out of a base "100" double dIndex = (double)(iRunningByteTotal); double dTotal = (double)byteBuffer.Length; double dProgressPercentage = (dIndex / dTotal); int iProgressPercentage = (int)(dProgressPercentage * 100); sw.Start(); dnSpeed.Text = string.Format("{0} kB/s", (iRunningByteTotal / 1024d / sw.Elapsed.TotalSeconds).ToString("0")); // update the progress bar worker.ReportProgress(iProgressPercentage); } // clean up the file stream streamLocal.Close(); } // close the connection to the remote server streamRemote.Close(); } } }
public async Task Info(string url) { { using (System.Net.WebClient webClient = new System.Net.WebClient()) { using (Stream stream = webClient.OpenRead(url)) { var image = new Discord.Image(stream); await Context.Client.CurrentUser.ModifyAsync(u => u.Avatar = image); } } } }