DownloadData() public method

public DownloadData ( System address ) : byte[]
address System
return byte[]
        public decimal GetConvertion(string from, string to)
        {
            WebClient objWebClient = null;
            UTF8Encoding objUTF8 = null;
            decimal result = 0;

            try{
                objWebClient = new WebClient();
                objUTF8 = new UTF8Encoding();

                byte[] aRequestedHTML = objWebClient.DownloadData(String.Format("http://www.xe.com/ucc/convert/?Amount=1&From={0}&To={1}", from, to));
                string strRequestedHTML = objUTF8.GetString(aRequestedHTML);

                int search1 = strRequestedHTML.LastIndexOf("&nbsp;<span class=\"uccResCde\">USD</span>");
                string search2 = strRequestedHTML.Substring(search1 - 21, 21);
                int search3 = search2.LastIndexOf(">");
                string stringRepresentingCE = search2.Substring(search3 + 1);

                result = Convert.ToDecimal(stringRepresentingCE.Trim());

            }
            catch (Exception ex){
                // Agregar codigo para manejar la excepción.
            }

            return result;
        }
Ejemplo n.º 2
1
        /// <summary>
        /// method to download the contents of a file from a remote URI
        /// </summary>
        /// <param name="ftpUri"></param>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public static string GetFileFromSite(Uri ftpUri, string user, string pass)
        {
            string fileString = string.Empty;

            // The serverUri parameter should start with the ftp:// scheme.
            if (ftpUri.Scheme != Uri.UriSchemeFtp)
            {
                return string.Empty;
            }
            // Get the object used to communicate with the server.
            WebClient request = new WebClient();

            // This example assumes the FTP site uses anonymous logon.
            NetworkCredential nc = new NetworkCredential(user, pass);
            CredentialCache cc = new CredentialCache();
            cc.Add(ftpUri, "Basic", nc);
            request.Credentials = cc;

            try
            {

                byte[] newFileData = request.DownloadData(ftpUri.ToString());
                fileString = System.Text.Encoding.UTF8.GetString(newFileData);
            }
            catch (WebException e)
            {
                m_logger.WriteToLogFile("FtpUtils::GetFileFromSite();ECaught: " + e.Message);
            }
            return fileString;
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            var wc = new WebClient();
            wc.UploadFile("http://*****:*****@"C:\rest\Nowy dokument tekstowy.txt");

            Console.WriteLine("Upload done");

            DownloadFileAsync(@"C:\rest1\encypt", "encrypt").Wait();
            Console.WriteLine("Encrypt done");

            DownloadFileAsync(@"C:\rest1\decrypt.txt", "decrypt").Wait();
            Console.WriteLine("Decrypt done");

            Console.WriteLine("MD5 SUM:");
            byte[] md5 = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=MD5");
            foreach (var item in md5)
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("SHA SUM");
            byte[] sha = wc.DownloadData("http://localhost:1729/api/Bib2/GetSum?optionSum=SHA");
            foreach (var item in sha)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
Ejemplo n.º 4
0
        public ActionResult GetAvatar(int size)
        {
            string uid = Session["currentUserId"].ToString();
            AccountModel user = null;
            byte[] avatar = null;

            using (var db = new AppContext())
            {
                user = db.Accounts.Where(a => a.WeiboId == uid).ToList().First();
            }

            using (var client = new WebClient())
            {
                switch (size)
                {
                    case 50:
                        avatar = client.DownloadData(user.Avatar50Url);
                        break;
                    case 180:
                    default:
                        avatar = client.DownloadData(user.Avatar180Url);
                        break;
                }
            }

            return File(avatar, "image/jpeg");
        }
Ejemplo n.º 5
0
 private static bool GetUpdateInfo(out UpdateInfo info)
 {
     const string keyLink = "link =";
     const string keyVersion = "version =";
     info = default(UpdateInfo);
     using (var client = new WebClient())
     {
         try
         {
             var data = client.DownloadData(UpdateUrl + "index.txt");
             var updIndex = Encoding.Default.GetString(data).Split('\n');
             var updInfo = new StringBuilder();
             for (var i = 0; i < updIndex.Length; i++)
             {
                 var buf = updIndex[i].Trim();
                 var version = new Version(buf);
                 if (version <= Root.Version)
                     continue;
                 info.IsNewer = true;
                 for (var j = i; j < updIndex.Length; j++)
                 {
                     data = client.DownloadData(UpdateUrl + updIndex[j].Trim() + ".txt");
                     var lines = Encoding.Default.GetString(data).Split('\n');
                     for (var k = 0; k < lines.Length; k++)
                     {
                         updInfo.Append(lines[k]);
                         updInfo.Append("\r\n");
                     }
                     updInfo.Append("\r\n\r\n");
                 }
                 break;
             }
             if (updInfo.Length == 0)
                 return true;
             info.Description = updInfo.ToString();
             data = client.DownloadData(UpdateUrl + "latest.txt");
             updIndex = Encoding.Default.GetString(data).Split('\n');
             for (var i = 0; i < updIndex.Length; i++)
             {
                 if (updIndex[i].StartsWith(keyLink))
                 {
                     info.Link = updIndex[i].Substring(keyLink.Length).Trim();
                     continue;
                 }
                 if (updIndex[i].StartsWith(keyVersion))
                 {
                     info.Version = updIndex[i].Substring(keyVersion.Length).Trim();
                     break;
                 }
             }
             return true;
         }
         catch (Exception)
         {
             //Log("! Update attempt failed: " + e.Message);
             return false;
         }
     }
 }
 public void TestFixtureSetUp()
 {
     using (var c = new WebClient())
     {
         _examples[true] = c.DownloadData(ValidXhtmlUrl);
         _examples[false] = c.DownloadData(InvalidXhtmlUrl);
     }
 }
        /// <summary>
        /// Update manufacturer settings from the Gurux www server.
        /// </summary>
        /// <returns>Returns directory where backups are made. Return null if no backups are made.</returns>
        public static string UpdateManufactureSettings()
        {
            string backupPath = Path.Combine(ObisCodesPath, "backup");

            if (!System.IO.Directory.Exists(backupPath))
            {
                System.IO.Directory.CreateDirectory(backupPath);
            }
            backupPath = Path.Combine(backupPath, Guid.NewGuid().ToString());
            System.Net.WebClient client = new System.Net.WebClient();
            IWebProxy            proxy  = WebRequest.GetSystemWebProxy();

            if (proxy != null && proxy.Credentials != null)
            {
                client.Proxy = proxy;
            }
            //This will fix the error: request was aborted could not create ssl/tls secure channel.
            //For Net45 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            byte[] files = client.DownloadData("https://www.gurux.fi/obis/files.xml");
            System.IO.File.WriteAllBytes(Path.Combine(ObisCodesPath, "files.xml"), files);
            Gurux.DLMS.ManufacturerSettings.GXFileInfo.UpdateFileSecurity(Path.Combine(ObisCodesPath, "files.xml"));
            // Put the byte array into a stream and rewind it to the beginning
            MemoryStream ms = new MemoryStream(files);

            ms.Flush();
            ms.Position = 0;
            XmlDocument xml = new XmlDocument();

            xml.Load(ms);
            bool backup = false;

            foreach (XmlNode it in xml.ChildNodes[1].ChildNodes)
            {
                string path = Path.Combine(ObisCodesPath, it.InnerText);
                byte[] data = client.DownloadData("https://www.gurux.fi/obis/" + it.InnerText);
                //Make backup if file exists or content has change.
                if (System.IO.File.Exists(path) && GetMD5Hash(data) != GetMD5HashFromFile(path))
                {
                    if (!System.IO.Directory.Exists(backupPath))
                    {
                        System.IO.Directory.CreateDirectory(backupPath);
                    }
                    backup = true;
                    System.IO.File.Copy(path, Path.Combine(backupPath, it.InnerText));
                }
                System.IO.File.WriteAllBytes(path, data);
                Gurux.DLMS.ManufacturerSettings.GXFileInfo.UpdateFileSecurity(path);
            }
            if (backup)
            {
                return(backupPath);
            }
            return(null);
        }
Ejemplo n.º 8
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length == 0 || !(textBox1.Text.ToLowerInvariant().StartsWith("http://www.youtube.com/watch?v=") || textBox1.Text.ToLowerInvariant().StartsWith("www.youtube.com/watch?v=") || textBox1.Text.ToLowerInvariant().StartsWith("youtube.com/watch?v=")))
            {
                MessageBox.Show("Please enter a valid YouTube URL!");
                return;
            }

            richTextBox1.Clear();
            richTextBox1.Text = "Retrieving...";
            richTextBox1.Refresh();
            if (textBox1.Text.ToLowerInvariant().StartsWith("youtube.com/watch?v="))
                textBox1.Text = "http://www." + textBox1.Text;
            if (textBox1.Text.ToLowerInvariant().StartsWith("www.youtube.com/watch?v="))
                textBox1.Text = "http://" + textBox1.Text;
            try
            {
                WebClient wc = new WebClient();
                byte[] response = wc.DownloadData(textBox1.Text);
                string content = Encoding.ASCII.GetString(response);
                content = content.Substring(content.IndexOf("<p id=\"watch-uploader-info\">") + 28);
                int start = content.IndexOf("<") + 9;
                int stop;
                content = content.Substring(start);
                if (!content.StartsWith(@"/user/"))
                {
                    content = content.Substring(content.IndexOf("<") + 1);
                    content = content.Substring(content.IndexOf("<"));
                    start = content.IndexOf("<") + 9;
                    stop = content.IndexOf("class", start) - 2;
                    content = content.Substring(start, stop - start);
                }
                else
                {
                    stop = content.IndexOf("class") - 2;
                    content = content.Substring(0, stop);
                }
                string channel = "http://youtube.com" + content;
                string line1 = "Uploader Channel: " + channel;
                response = wc.DownloadData(channel);
                content = Encoding.ASCII.GetString(response);
                content = content.Substring(content.IndexOf("<span class=\"stat-value\">") + 25);
                string line2 = "\r\nSubscribers: " + content.Substring(0, content.IndexOf("<"));
                content = content.Substring(content.IndexOf("<span class=\"stat-value\">") + 25);
                string line3 = "\r\nVideo views: " + content.Substring(0, content.IndexOf("<"));
                richTextBox1.Text = line1;
                richTextBox1.Text += line2;
                richTextBox1.Text += line3;
                richTextBox1.Refresh();
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message);
            }
        }
Ejemplo n.º 9
0
        public void ProcessRequest(HttpContext context)
        {
            Logger logger = LogManager.GetCurrentClassLogger();
            try
            {
                WebClient webClient = new WebClient();
                string login = "", pass = "";
                login = ConfigurationManager.AppSettings["loginForService"];
                pass = ConfigurationManager.AppSettings["passwordForService"];
                webClient.Credentials = new NetworkCredential(login, pass);

                byte[] arrMain;
                byte[] arrMicro;
                byte[] arrExtraAttachment;

                if ((context.Session["SilabMainResultUri"] != null) && (context.Request.Form["Main"] != null || context.Request.QueryString["Main"] != null))
                {
                    arrMain = webClient.DownloadData(context.Session["SilabMainResultUri"].ToString());
                    context.Response.Clear();
                    context.Response.AppendHeader("Content-Disposition", "attachment; filename=SynevoResults" + context.Session["barcode"] + ".pdf");
                    context.Response.ContentType = "application/pdf";
                    context.Response.BinaryWrite(arrMain);
                    context.Response.Flush();
                }
                if ((context.Session["SilabMicroResultUri"] != null) && (context.Request.Form["Micro"] != null || context.Request.QueryString["Micro"] !=null))
                {
                    arrMicro = webClient.DownloadData(context.Session["SilabMicroResultUri"].ToString());
                    context.Response.Clear();
                    context.Response.AppendHeader("Content-Disposition", "attachment; filename=SynevoResults" + context.Session["barcode"] + "_Micro.pdf");
                    context.Response.ContentType = "application/pdf";
                    context.Response.BinaryWrite(arrMicro);
                    context.Response.Flush();
                }
                if ((context.Session["ExtraAttachmentUri"] != null) && (context.Request.Form["ExtraAttachment"] != null || context.Request.QueryString["ExtraAttachment"] != null))
                {
                    ArrayList arrExtraAttachment_ = (ArrayList)context.Session["ExtraAttachmentUri"];
                    arrExtraAttachment = webClient.DownloadData(arrExtraAttachment_[0].ToString());
                    context.Response.Clear();
                    context.Response.AppendHeader("Content-Disposition", "attachment; filename=SynevoAddResults" + context.Session["barcode"] + "_Add.pdf");
                    context.Response.ContentType = "application/pdf";
                    context.Response.BinaryWrite(arrExtraAttachment);
                    context.Response.Flush();
                }
            }
            catch (System.Threading.ThreadAbortException ex)
            {
                logger.Warn(ex.Message + " | Row: " + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')));
            }
            catch (Exception ex)
            {
                logger.Warn(ex.Message + " | Row: " + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')));
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            try
            {
                // Get url.
                string url = "http://edu.regi.rovno.ua/";

                // Report url.
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("... PageTimeTest: times web pages");
                Console.ResetColor();
                Console.WriteLine("Testing: {0}", url);
                
                // Fetch page.
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    // Set gzip.
                    client.Headers["Accept-Encoding"] = "gzip";

                    // Download.
                    // ... Do an initial run to prime the cache.
                    byte[] data = client.DownloadData(url);

                    // Start timing.
                    Stopwatch stopwatch = Stopwatch.StartNew();

                    // Iterate.
                    for (int i = 0; i < Math.Min(100, _max); i++)
                    {
                        data = client.DownloadData(url);
                    }

                    // Stop timing.
                    stopwatch.Stop();

                    // Report times.
                    Console.WriteLine("Time required: {0} ms",
                        stopwatch.Elapsed.TotalMilliseconds); //повний час загрузки
                    Console.WriteLine("Time per page: {0} ms",
                        stopwatch.Elapsed.TotalMilliseconds / _max); //середній час загрузки
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("[Done]");
                Console.ReadLine();
            }
        }
Ejemplo n.º 11
0
        public DomeWindow()
        {
            Globals.Status       = "Initialising dome window";
            Globals.LoadProgress = 40;

            InitializeComponent();

            Screen[] sc;
            sc = Screen.AllScreens;

            if (!Globals.testing && sc.Length > 2)
            {
                this.WindowState   = FormWindowState.Normal;
                this.Left          = sc[2].Bounds.Left;
                this.Top           = sc[2].Bounds.Top;
                this.StartPosition = FormStartPosition.Manual;
                this.WindowState   = FormWindowState.Maximized;
            }

            Globals.Status       = "Downloading AllSky image";
            Globals.LoadProgress = 50;

            System.Net.WebClient   client = new System.Net.WebClient();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            byte[] data = null;

            try {
                if (Globals.SunHor.alt < 0)
                {
                    data = client.DownloadData("http://star.herts.ac.uk/allsky/camera1/AllSkyCurrentImage.JPG");
                }
                else
                {
                    data = client.DownloadData("http://star.herts.ac.uk/allsky/camera7/AllSkyCurrentImage.JPG");
                }
                Globals.Status       = "Writing stream";
                Globals.LoadProgress = 60;

                stream.Write(data, 0, data.Length);
                pictureBox1.Image = Image.FromStream(stream);
            } catch {
                pictureBox1.Image = null;
            }

            Globals.Status       = "Connecting to dome";
            Globals.LoadProgress = 60;

            if (!Globals.testing)
            {
                connect();
            }
        }
Ejemplo n.º 12
0
        public System.IO.Stream Load(object source)
        {
            var webClient = new WebClient();
            byte[] html = null;

            if (source is string)
                html = webClient.DownloadData(source as string);
            else if (source is Uri)
                html = webClient.DownloadData(source as Uri);

            if (html == null || html.Count() == 0) return null;

            return new MemoryStream(html);
        }
Ejemplo n.º 13
0
        public static void BeginLoadImageFromSearch(string search, bool isRandom = true)
        {
            _currentSearch = search;
            ThreadPool.QueueUserWorkItem((s)=>
            {
                try
                {
                    //load google images page
                    var url = new Uri(string.Format(_urlScheme, Uri.EscapeDataString(search)));
                    var wc = new WebClient();
                    wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");
                    var str = wc.DownloadString(url);

                    //declarations
                    byte[] imgData = null;
                    int index1 = 0, index2 = 0;
                    //find first url
                    index1 = str.IndexOf(_parse1) + _parse1.Length;
                    //if random - skip some urls
                    if (isRandom)
                    {
                        var randomNumber = rand.Next(0, 5);
                        for (int i = 0; i < randomNumber; i++)
                            index1 = str.IndexOf(_parse1, index1) + _parse1.Length;
                    }
                    //find url end
                    index2 = str.IndexOf(_parse2, index1);
                    //download url
                    try
                    {
                        imgData = wc.DownloadData(new Uri(str.Substring(index1, index2 - index1)));
                    }
                    catch
                    {
                        //if download failed - try next url once
                        index1 = str.IndexOf(_parse1, index1) + _parse1.Length;
                        index2 = str.IndexOf(_parse2, index1);
                        imgData = wc.DownloadData(new Uri(str.Substring(index1, index2 - index1)));
                    }
                    //bytes to image
                    var image = ImageLoader.LoadImage(new MemoryStream(imgData));
                    //run event
                    if (_currentSearch == search && ImageLoaded != null)
                        ImageLoaded(null, image);
                }
                catch { if (ImageLoadFail != null) ImageLoadFail(null, null); }
            });
        }
Ejemplo n.º 14
0
 private static byte[] GetRBLoadNWC(String aslocation)
 {
     using (var client = new System.Net.WebClient())
     {
         return(client.DownloadData(aslocation));
     }
 }
Ejemplo n.º 15
0
        public string GetID(string PathTorrent, string ServerAdress)
        {
            System.Net.WebClient WC = new System.Net.WebClient();
            WC.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");
            WC.Encoding = System.Text.Encoding.UTF8;
            byte[] FileTorrent = WC.DownloadData(PathTorrent);

            string FileTorrentString = System.Convert.ToBase64String(FileTorrent);

            FileTorrent = System.Text.Encoding.Default.GetBytes(FileTorrentString);

            System.Net.WebRequest request = System.Net.WebRequest.Create("http://api.torrentstream.net/upload/raw");
            request.Method        = "POST";
            request.ContentType   = "application/octet-stream\\r\\n";
            request.ContentLength = FileTorrent.Length;
            System.IO.Stream dataStream = request.GetRequestStream();
            dataStream.Write(FileTorrent, 0, FileTorrent.Length);
            dataStream.Close();

            System.Net.WebResponse response = request.GetResponse();
            dataStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
            string responseFromServer     = reader.ReadToEnd();

            string[] responseSplit = responseFromServer.Split('\"');
            return(responseSplit[3]);
        }
Ejemplo n.º 16
0
        private void cmbCountries_SelectedIndexChanged(object sender, EventArgs e)
        {
            Guid Country_Id;

            Guid.TryParse(cmbCountries.SelectedValue.ToString(), out Country_Id);

            if (Country_Id != Guid.Empty)
            {
                System.Net.WebClient proxy = new System.Net.WebClient();
                byte[] data   = proxy.DownloadData("http://10.21.32.196:8080/Consumer.svc/GetCitiesByCountry/" + cmbCountries.SelectedValue.ToString());
                Stream stream = new MemoryStream(data);
                DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List <ConsumerService.DC_Master_City>));
                var result = obj.ReadObject(stream) as List <ConsumerService.DC_Master_City>;

                cmbCity.DataSource    = (from r in result select new { r.City_Id, r.City_Name }).ToList();
                cmbCity.ValueMember   = "City_Id";
                cmbCity.DisplayMember = "City_Name";
                cmbCity.Refresh();

                result = null;
                obj    = null;
                stream = null;
                data   = null;
                proxy  = null;
            }
        }
Ejemplo n.º 17
0
        private static System.IO.Stream Execute(string relativeUri)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] data             = wc.DownloadData(relativeUri);

            return(new System.IO.MemoryStream(data));
        }
            public async Task blb(int number = -1)
            {
                Math.Abs(number);
                Random rnd = new Random();

                if (number == -1)
                {
                    number = rnd.Next(0, 100);
                }
                if (number > 100 || number == 0)
                {
                    await ReplyAsync("Invalid number. Must be between 1 and 100.");

                    return;
                }

                System.Net.WebClient wc = new System.Net.WebClient();
                byte[] raw = wc.DownloadData("http://numbersapi.com/" + number);

                string webData = System.Text.Encoding.UTF8.GetString(raw);

                await ReplyAsync(webData);

                //http://numbersapi.com/100
            }
Ejemplo n.º 19
0
        protected string GetJsonData(string url)
        {
            string sContents = string.Empty;
            string me        = string.Empty;

            try
            {
                if (url.ToLower().IndexOf("https:") > -1)
                {
                    System.Net.WebClient client = new System.Net.WebClient();
                    byte[] response             = client.DownloadData(url);
                    sContents = System.Text.Encoding.ASCII.GetString(response);
                }
                else
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(url);
                    sContents = sr.ReadToEnd();
                    sr.Close();
                }
            }
            catch
            {
                sContents = "unable to connect to server ";
            }
            return(sContents);
        }
Ejemplo n.º 20
0
            public static string PostOAFileToUrl(string filename, string filepath, string url)
            {
                Encoding encoding  = Encoding.GetEncoding(REQUESTENCODING);
                Stream   memStream = new MemoryStream();

                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + BOUNDARY + "\r\n");
                memStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                string format = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

                string head = string.Format(format, filename, @"C:\" + filename);

                byte[] headBytes = Encoding.GetEncoding(REQUESTENCODING).GetBytes(head);

                memStream.Write(headBytes, 0, headBytes.Length);


                System.Net.WebClient myWebClient = new System.Net.WebClient();
                byte[] contentBytes = myWebClient.DownloadData(filepath);
                memStream.Write(contentBytes, 0, contentBytes.Length);

                memStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                //读取流字节
                memStream.Position = 0;
                byte[] tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Dispose();


                return(GetResult(tempBuffer, url));
            }
Ejemplo n.º 21
0
        protected string fileGetContents(string fileName)
        {
            string sContents = string.Empty;

            System.IO.StreamReader sr;
            string me = string.Empty;

            try
            {
                if (fileName.ToLower().IndexOf("https:") > -1)
                {
                    System.Net.WebClient wc = new System.Net.WebClient();
                    byte[] response         = wc.DownloadData(fileName);
                    sContents = System.Text.Encoding.ASCII.GetString(response);
                }
                else
                {
                    sr        = new System.IO.StreamReader(fileName);
                    sContents = sr.ReadToEnd();
                    sr.Close();
                }
            }
            catch (Exception)
            {
                sContents = "unable to connect to server";
            }

            return(sContents);
        }
Ejemplo n.º 22
0
 internal static bool IsValidServerVersion(Uri url)
 {
     using (WebClient client = new WebClient())
     {
         client.Headers[HttpRequestHeader.UserAgent] = CmdletContext.GetUserAgent();
         string str = null;
         try
         {
             client.DownloadData(url);
             str = client.ResponseHeaders[HEADER_SHAREPOINT_VERSION];
         }
         catch (WebException exception)
         {
             if ((exception != null) && (exception.Response != null))
             {
                 str = exception.Response.Headers[HEADER_SHAREPOINT_VERSION];
             }
         }
         if (str == null)
         {
             throw new InvalidOperationException("Could not connect to SharePoint Online.");
         }
         if (!string.IsNullOrEmpty(str))
         {
             Version version;
             string str2 = str.Split(new char[] { ',' })[0];
             if (Version.TryParse(str2, out version))
             {
                 return (version.Major >= 15);
             }
         }
     }
     return false;
 }
        private void backgroundWorkerDownloadLanguages_DoWork(object sender, DoWorkEventArgs e)
        {
            // Download / update languages:
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);

                byte[] raw     = wc.DownloadData("https://raw.githubusercontent.com/FelisDiligens/Fallout76-QuickConfiguration/master/Fo76ini/languages/list.txt");
                String encoded = Encoding.UTF8.GetString(raw).Trim();

                String[] list = encoded.Split('\n', ',');

                foreach (String file in list)
                {
                    wc.DownloadFile("https://raw.githubusercontent.com/FelisDiligens/Fallout76-QuickConfiguration/master/Fo76ini/languages/" + file, Path.Combine(Localization.languageFolder, file));
                }

                errorMessageDownloadLanguages = null;
                messageDownloadLanguages      = String.Join(", ", list);
                //MsgBox.Get("downloadLanguagesFinished").FormatText(String.Join(", ", list)).Popup(MessageBoxIcon.Information);
            }
            catch (WebException ex)
            {
                errorMessageDownloadLanguages = ex.ToString();
                messageDownloadLanguages      = null;
                //MsgBox.Get("downloadLanguagesFailed").FormatText(ex.ToString()).Popup(MessageBoxIcon.Error);
            }
            catch
            {
                errorMessageDownloadLanguages = "Unknown error";
                messageDownloadLanguages      = null;
                //MsgBox.Get("downloadLanguagesFailed").FormatText("Unknown error").Popup(MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 读取一个url
        /// </summary>
        /// <param name="WebUrl"></param>
        /// <param name="CreatPath"></param>
        public static string CetHtml(string WebUrl)
        {
            string content = "";
            try
            {
                HttpResponse response = HttpContext.Current.Response;
                HttpRequest request = HttpContext.Current.Request;

                //调用Main_Execute,并且获取其输出
                StringWriter sw = new StringWriter();

                //HttpContext.Current.Server.Execute(executePath, sw);
                //content = sw.ToString();

                //string url = "http://" + HttpContext.Current.Request.Url.Authority + WebUrl;
                string url = WebUrl;
                System.Net.WebClient wc = new System.Net.WebClient();
                byte[] b = wc.DownloadData(url);
                content = System.Text.Encoding.GetEncoding("utf-8").GetString(b);

            }
            catch (Exception ex)
            {

                //throw ex;
                return "error";
            }
            return content;
        }
Ejemplo n.º 25
0
        /// <summary>
        /// LibraryFetcher 
        /// </summary>
        public LibraryFetcher()
        {
            try
            {
                // 1. download xmlList
                byte[] data;
                using (WebClient client = new WebClient())
                {
                    string uriPlmPackLib = Settings.Default.UriPlmPackLib;
                    if (!uriPlmPackLib.EndsWith("/"))
                        uriPlmPackLib += "/";
                    data = client.DownloadData(uriPlmPackLib + "xml/LibraryList.xml" );
                }
                string localFilePath = Path.Combine(Path.GetTempPath(), "LibraryList.xml");
                File.WriteAllBytes(localFilePath, data);

                // 2. if directory PLMPackLib_ThumbCache does not exist create it
                string thumbCacheDirectory = Path.Combine(Path.GetTempPath(), Library.ImageDirectory);
                if (!Directory.Exists(thumbCacheDirectory))
                    Directory.CreateDirectory(thumbCacheDirectory);

                // 3. load file
                ListOfLibraries listOfLibraries = ListOfLibraries.LoadFromFile(localFilePath);
                _libraries = listOfLibraries.Library;
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
Ejemplo n.º 26
0
        public void DownloadJson(ConnectionEntity connectionEntity, string filepath)
        {
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);

            var typePart = connectionEntity.ToString().ToLower();           
            var uri = new Uri(_baseUri + "/" + typePart + ".json");

            string fileName = filepath + "\\" + typePart + ".json";
            WebClient client = new WebClient();

            using (StreamReader reader = new StreamReader(new MemoryStream(client.DownloadData(uri))))
            {
                var content = reader.ReadToEnd();
                JArray jsonArray = JArray.Parse(content);               

                using (StreamWriter writer = new StreamWriter(File.Create(fileName)))
                {
                    foreach (var item in jsonArray.Children())
                    {
                        writer.WriteLine(item.ToString(Newtonsoft.Json.Formatting.None));
                    }
                }
            }              
        }
Ejemplo n.º 27
0
        private List<Models.File> DownloadRepoFiles(string downloadUrl) {
            List<Models.File> results = new List<Models.File>();
            using (var wc = new WebClient()) {

                byte[] tarball = wc.DownloadData(downloadUrl);
                using (var zip = ZipFile.Read(new MemoryStream(tarball))) {
                    string dir = "";
                    if (zip.Count > 0) {
                        dir = zip[0].FileName;
                    }

                    foreach (var file in zip) {
                        if (!file.IsDirectory) {
                            var fileStream = new MemoryStream();
                            file.Extract(fileStream);

                            byte[] content = fileStream.ToArray();
                            string filename = file.FileName.Replace(dir, "");

                            Models.File repositoryFile = new Models.File {
                                Content = content,
                                Filename = filename,
                                Size = content.Length,
                                Include = true
                            };

                            results.Add(repositoryFile);
                        }
                    }
                }
            }

            return results;
        }
Ejemplo n.º 28
0
        public static List<IPRangeCountry> Download()
        {
            using (var client = new WebClient())
            {
                byte[] zippedData =
                    client.DownloadData("http://download.ip2location.com/lite/IP2LOCATION-LITE-DB1.CSV.ZIP");

                using (var zippedFileStream = new MemoryStream(zippedData))
                using (ZipFile zipFile = ZipFile.Read(zippedFileStream))
                {
                    ZipEntry compressedFileInZip = zipFile.SelectEntries("*.csv").FirstOrDefault();
                    using (var csvStream = new MemoryStream())
                    {
                        compressedFileInZip.Extract(csvStream);
                        csvStream.Position = 0;
                        using (var textReader = new StreamReader(csvStream))
                        using (var csv = new CsvReader(textReader))
                        {
                            csv.Configuration.RegisterClassMap<IPRangeCountryMap>();
                            csv.Configuration.HasHeaderRecord = false;
                            csv.Read();
                            return csv.GetRecords<IPRangeCountry>().ToList();
                        }
                    }
                }
            }
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            Console.Write("Please enter string to search google for: ");
             string searchString = HttpUtility.UrlEncode(Console.ReadLine());

             Console.WriteLine();
             Console.Write("Please wait...\r");

             // Query google.
             WebClient webClient = new WebClient();
             byte[] response =
              webClient.DownloadData("http://www.google.com/search?&num=5&q="
              + searchString);

             // Check response for results
             string regex = "g><a\\shref=\"?(?<URL>[^\">]*)[^>]*>(?<Name>[^<]*)";
             MatchCollection matches
                  = Regex.Matches(Encoding.ASCII.GetString(response), regex);

             // Output results
             Console.WriteLine("===== Results =====");
             if(matches.Count > 0)
             {
            foreach(Match match in matches)
            {
               Console.WriteLine(HttpUtility.HtmlDecode(
                  match.Groups["Name"].Value) +
                  " - " + match.Groups["URL"].Value);
            }
             }
             else
             {
            Console.WriteLine("0 results found");
             }
        }
Ejemplo n.º 30
0
        public string downloadBinaryFile_Action(string urlOfFileToFetch, string targetFileOrFolder)
        {
            if (urlOfFileToFetch.is_Null() || targetFileOrFolder.is_Null())
                return null;
            var targetFile = targetFileOrFolder;
            if (Directory.Exists(targetFileOrFolder))
                targetFile = targetFileOrFolder.pathCombine(urlOfFileToFetch.fileName());

            PublicDI.log.debug("Downloading Binary File {0}", urlOfFileToFetch);
            lock (this)
            {
                using (var webClient = new WebClient())
                {
                    try
                    {
                        byte[] pageData = webClient.DownloadData(urlOfFileToFetch);
                        O2Kernel_Files.WriteFileContent(targetFile, pageData);
                        PublicDI.log.debug("Downloaded File saved to: {0}", targetFile);

                        webClient.Dispose();

                        GC.Collect();       // because of WebClient().GetRequestStream prob
                        return targetFile;
                    }
                    catch (Exception ex)
                    {
                        PublicDI.log.ex(ex);
                    }
                }
            }
            GC.Collect();       // because of WebClient().GetRequestStream prob
            return null;
        }
Ejemplo n.º 31
0
        // *TO OPEN CONSOLE ON LAUNCH*

        // [DllImport("kernel32.dll", SetLastError = true)]
        // [return: MarshalAs(UnmanagedType.Bool)]
        // static extern bool AllocConsole();

        private void Form1_Load(object sender, EventArgs e)
        {
            msmMain.Theme = MetroFramework.MetroThemeStyle.Dark;
            msmMain.Style = (MetroFramework.MetroColorStyle) 3;
            string currentversion = LimeLight_Gaming_Launcher.Properties.Settings.Default.version;

            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] raw = wc.DownloadData("http://pastebin.com/raw/PZg7Jwm7");

            string webData = Encoding.UTF8.GetString(raw);

            lblScroll.Text = "     " + webData;

            if (lblScroll.Text.Contains(currentversion))
            {
            }
            else
            {
                string            updatemessage = "A New Update Is Available, Would You Like To Download It Now?";
                string            updatecaption = "Update Available";
                MessageBoxButtons updatebuttons = MessageBoxButtons.YesNo;
                DialogResult      result;

                result = MessageBox.Show(updatemessage, updatecaption, updatebuttons);

                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    Process.Start("https://mega.nz/#F!dY0GgZCT!qkkICH0GQdj4ibqs_lz2Wg");
                    Environment.Exit(0);
                }
            }


            serverstatsload();
        }
Ejemplo n.º 32
0
        //下载
        //文件保存在另一个站点,无法读取文件流
        //直接将IIS的MIME类型 .pdf  设置为application/octet-stream,但是在谷歌下不能兼容
        protected void ResourceDownload(object sender, EventArgs e)
        {
            string cms_path = Common.CMS_URL + info.ResourcePath;

            WebClient client = new WebClient();
            try
            {
                byte[] data = client.DownloadData(cms_path);

                if (data.Length != 0)
                {
                    System.Web.HttpContext.Current.Response.Clear();
                    System.Web.HttpContext.Current.Response.ClearHeaders();
                    System.Web.HttpContext.Current.Response.Buffer = false;
                    System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
                    System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(cms_path), System.Text.Encoding.UTF8));
                    System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", data.Length.ToString());
                    System.Web.HttpContext.Current.Response.BinaryWrite(data);
                    System.Web.HttpContext.Current.Response.Flush();
                    System.Web.HttpContext.Current.Response.End();
                }
            }
            catch (Exception)
            {

            }
        }
 public byte[] Download(string resourcePath)
 {
     using (var client = new WebClient())
     {
         return client.DownloadData(resourcePath);
     }
 }
Ejemplo n.º 34
0
        public static Stream GetStreamFromUrl(string url)
        {
            if (!Directory.Exists("temp"))
            {
                Directory.CreateDirectory("temp");
            }

            if (KeyValue.Count(t => t.Key == url) > 0)
            {
                string path = "temp/" + KeyValue.First(t => t.Key == url).Value;
                return(new MemoryStream(File.ReadAllBytes(path)));
            }

            byte[] imageData = null;

            using (var wc = new System.Net.WebClient())
                imageData = wc.DownloadData(url);

            string value = Guid.NewGuid().ToString();

            File.WriteAllBytes("temp/" + value, imageData);
            KeyValue.Add(new KeyValuePair <string, string>(url, value));

            return(new MemoryStream(imageData));
        }
        //protected override void OnPreRender(EventArgs e)
        //{
        //    base.OnPreRender(e);
        //}

        protected void gvUploadedFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            if (e.CommandName == "deleteRecord")
            {
                string file = e.CommandArgument.ToString();
                ViewState["FilesToDelete"] = file;
                DeleteAttachment();
                FillDocument();
            }
            if (e.CommandName == "DownloadRecord")
            {
                string       file     = e.CommandArgument.ToString();
                string       filePath = ("~\\UploadedFiles" + "\\" + file);
                string       strUrl   = filePath;
                WebClient    req      = new System.Net.WebClient();
                HttpResponse response = HttpContext.Current.Response;
                Response.Clear();
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.Buffer = true;
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filePath);
                byte[] data = req.DownloadData(Server.MapPath(strUrl));
                Response.ContentType = "application/doc";
                response.BinaryWrite(data);
                response.End();
            }
        }
Ejemplo n.º 36
0
        private void button3_Click(object sender, EventArgs e)
        {
            string pageUrl = "http://book.douban.com/subject_search?search_text=%E6%95%B0%E5%AD%A6%E4%B9%8B%E7%BE%8E&cat=1001";
            WebClient wc = new WebClient();
            byte[] pageSourceBytes = wc.DownloadData(new Uri(pageUrl));
            string pageSource = Encoding.GetEncoding("utf-8").GetString(pageSourceBytes);

            //webBrower.Navigate(pageUrl);
            //webBrower.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowserComplete);

            MatchCollection mc = Regex.Matches(pageSource, @"<\s?img[^>]+src=""([^""]+)""");//使用正则表达式进行匹配,因为所获的图片较多,所以常见一个List集合储存;
            List<string> pic = new List<string>();
            foreach (Match m in mc)//进行遍历
            {
                if (m.Success)//若是能够匹配的字符串放到pic集合中
                {
                    pic.Add(m.Groups[1].Value.Trim());//获得图片 src="~~~"的形式;提取图片名称
                }

            }
            foreach (string picture in pic)
            {
                listBox1.Items.Add(picture);
            }
        }
Ejemplo n.º 37
0
        public void check_uploader()
        {
            string rnd      = this.random();
            string mp4Key   = GetTimeStamp() + "/" + rnd + ".mp4";
            string filepath = "H:/手机备份/手机/图片/VID_20170407_171319.mp4";

            Upoader up = new Upoader();

            up.init();
            string retstring = up.PutFile(mp4Key, filepath);

            if (retstring == "")
            {
                //删除目标文件。已经上传成功,不需要保留了。
                //回调

                string    filecode = this.fcode;
                string    status   = "1";
                WebClient client   = new System.Net.WebClient();
                string    uri      = "http://www.jianpianzi.com/cloud/transcodeStatus?status=1&filecode=" + filecode + "&mp4file=http://cdn.jianpianzi.com/" + mp4Key;
                byte[]    bt       = client.DownloadData(uri);
                Conn.ExecuteNonQuery("update ov_files set stat=2 where id=" + this.id);

                this.statini.WriteString("encoder", "uploadret", "url=" + uri);
                //System.IO.FileStream fs = System.IO.File.Create("c:\\encoderupload.txt");
                //fs.Write(bt, 0, bt.Length);
                //fs.Close();
                //修改数据库的地址为七牛
                this.AppendLog("encoder" + "uploadret" + "url=" + uri);
            }
        }
Ejemplo n.º 38
0
        private void btnParser_Click(object sender, EventArgs e)
        {
            #region 获得网页的html
            try
            {
                richTextBox1.Text = "";
                string url = textBox1.Text.Trim();
                System.Net.WebClient aWebClient = new System.Net.WebClient();
                aWebClient.Encoding = Encoding.GetEncoding("GBK");
                string html = Encoding.UTF8.GetString(aWebClient.DownloadData(url));
                richTextBox1.Text = html;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            #endregion

            #region 分析网页html节点
            Lexer    lexer     = new Lexer(this.richTextBox1.Text);
            Parser   parser    = new Parser(lexer);
            NodeList htmlNodes = parser.Parse(null);
            this.treeView1.Nodes.Clear();
            this.treeView1.Nodes.Add("root");
            TreeNode treeRoot = this.treeView1.Nodes[0];
            for (int i = 0; i < htmlNodes.Count; i++)
            {
                this.RecursionHtmlNode(treeRoot, htmlNodes[i], false);
            }

            #endregion
        }
Ejemplo n.º 39
0
 private void ShowPDFFile(string path)
 {
     try
     {
         if (Request.Browser.Type.ToUpper().Contains("IE"))
         {
             if (File.Exists(path))
             {
                 System.Net.WebClient client = new System.Net.WebClient();
                 Byte[] buffer = client.DownloadData(path);
                 if (buffer != null)
                 {
                     Response.ContentType = "application/pdf";
                     Response.AddHeader("content-length", buffer.Length.ToString());
                     Response.BinaryWrite(buffer);
                 }
                 System.IO.File.Delete(path);
                 Response.End();
             }
         }
         else
         {
             Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "PrintPdf.aspx?file=" + Server.UrlEncode(path)));
         }
     }
     catch (Exception ex)
     {
         EventLogger log = new EventLogger(config);
         log.LogException(ex);
         ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", Constant.FacilityVendorAccountErrorMessage.Replace("<<FacilityDescription>>", ex.Message.ToString()), true);
     }
 }
Ejemplo n.º 40
0
 public byte[] GetImage(string url)
 {
     using (var client = new WebClient())
     {
         return client.DownloadData(url);
     }
 }
Ejemplo n.º 41
0
        public static string Request(string sUrl, string sMethod, out string sMessage)
        {
            try
            {
                sMessage = "";
                using (System.Net.WebClient client = new System.Net.WebClient())
                {
                    client.Credentials = CreateAuthenticateValue(sUrl);
                    skyinforHttpAPI.SetHeaderValue(client.Headers, "accept", "application/json");

                    Uri    url    = new Uri(sUrl);
                    byte[] buffer = new byte[] { };
                    if (sMethod.ToUpper().Equals("GET"))
                    {
                        buffer = client.DownloadData(url);
                    }
                    return(Encoding.UTF8.GetString(buffer));
                }
            }
            catch (WebException ex)
            {
                sMessage = ex.Message;
                var rsp            = ex.Response as HttpWebResponse;
                var httpStatusCode = rsp.StatusCode;
                var authenticate   = rsp.Headers.Get("WWW-Authenticate");
                return("");
            }
            catch (Exception ex)
            {
                sMessage = ex.Message;
                return("");
            }
        }
Ejemplo n.º 42
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text=="")
            {
                MessageBox.Show("请填写单词,不要为空!谢谢!","提示");
            }
            else
            {
                richTextBox1.Clear();
                WebClient we = new WebClient();
                byte[] myDataBuffer;
                we.Headers.Add("user-agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
                try
                {
                    myDataBuffer = we.DownloadData("https://translate.google.com.hk/translate_a/t?client=t&sl=en&tl=zh-CN&hl=zh-CN&sc=2&ie=UTF-8&oe=UTF-8&prev=enter&ssel=0&tsel=0&q=" + textBox1.Text);
                }
                catch (WebException ex)
                {
                    //MessageBox.Show("服务器异常,请检查网络!","Error");
                    MessageBox.Show(ex.Message);
                    throw;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    throw;
                }

                string download = Encoding.UTF8.GetString(myDataBuffer);
                richTextBox1.AppendText(download);
            }
        }
        public void Process(System.Web.HttpResponse response)
        {
            response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(_filePath));
            response.AddHeader("Content-Transfer-Encoding", "binary");
            response.ContentType = "application/octet-stream";
            response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (_filePath.StartsWith("http"))
            {
                System.Net.WebClient net = new System.Net.WebClient();

                var file = net.DownloadData(_filePath);

                response.BinaryWrite(file);

                response.End();


            }
            else
            {
                response.WriteFile(_filePath);
            }


        }
Ejemplo n.º 44
0
		static string GetData(Uri uri)
		{
			var wc = new WebClient();
			wc.Proxy = null;
			var data = wc.DownloadData(uri);
			return Encoding.UTF8.GetString(data);
		}
Ejemplo n.º 45
0
 public static string[][] GetTorrents(string address, string username, string password)
 {
     WebClient wc = new WebClient();
     wc.Credentials = new NetworkCredential(username, password);
     string fullAddress = "http://" + address + "/gui/?list=1";
     //Fetch a raw listing of the current stuff from uTorrent==============================================
     byte[] rawResponse = wc.DownloadData(fullAddress);
     string response = Encoding.ASCII.GetString(rawResponse);
     Regex arrayBuilder = new Regex("\n");
     char[] delimiters = new char[] { '"', '[', ']' };
     int start = response.IndexOf('"' + "torrents" + '"' + ": [") + 16;
     int end = response.Length - (start + 29);
     response = response.Substring(start, end);
     //Clean the list text so its just the torrents=======================================================
     string[] rawTorrents = arrayBuilder.Split(response);
     string[][] torrents = new string[rawTorrents.Count()][];
     if (rawTorrents.Count() > 0)                //check for active torrents
     {
         for (int i = 0; i < rawTorrents.Count(); ++i)
         {
             string rawTorrent = rawTorrents[i];
             string[] tempTorrent = rawTorrent.Split(new Char[] { ',' });
             //now we fill the array torrents with: 0 = Hash, 1 = Status, 2 = Label, and 3 = Queue
             torrents[i] = new string[] { tempTorrent[0].ToString().Trim(delimiters), tempTorrent[1].ToString().Trim(delimiters), tempTorrent[11].ToString().Trim(delimiters), tempTorrent[17].ToString().Trim(delimiters), tempTorrent[2].ToString().Trim(delimiters) };
         }
     }
     return torrents;
 }
Ejemplo n.º 46
0
 public static void LabelTorrent(string address, string username, string password, string hash, string label)
 {
     WebClient wc = new WebClient();
     wc.Credentials = new NetworkCredential(username, password);
     string fullAddress = "http://" + address + "/gui/?action=setprops&hash=" + hash + "&s=label&v="+label;
     wc.DownloadData(fullAddress);
 }
Ejemplo n.º 47
0
        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            var result = WeatherService.GetWeatherFor(SearchBox.Text);

            string fileUrl = $"{Environment.CurrentDirectory}/{result.icon}.gif";

            if (!File.Exists(fileUrl))
            {
                using (var webClient = new WebClient())
                {
                    byte[] bytes = webClient.DownloadData(result.icon_url);
                    File.WriteAllBytes(fileUrl, bytes);
                }
            }

            BitmapImage image = new BitmapImage(new Uri(fileUrl));

            WeatherImage.Source = image;

            // CityBlock.Text = result.full.ToString();
            LatiLongBlock.Text = result.latitude.ToString() + "/" + result.longitude.ToString();
            WeatherBlock.Text = result.weather.ToString();
            TempFBlock.Text = result.temp_f.ToString();
            TempCBlock.Text = result.temp_c.ToString();
            HumidityBlock.Text = result.relative_humidity.ToString();
            WindmphBlock.Text = result.wind_mph.ToString();
            WindDirectionBlock.Text = result.wind_dir.ToString();
            UVIndexBox.Text = result.UV.ToString();

        }
Ejemplo n.º 48
0
        /// <summary>
        /// Type=2 群消息。
        /// </summary>
        /// <param name="subType">子类型,目前固定为1。</param>
        /// <param name="sendTime">发送时间(时间戳)。</param>
        /// <param name="fromGroup">来源群号。</param>
        /// <param name="fromQQ">来源QQ。</param>
        /// <param name="fromAnonymous">来源匿名者。</param>
        /// <param name="msg">消息内容。</param>
        /// <param name="font">字体。</param>
        public override void GroupMessage(int subType, int sendTime, long fromGroup, long fromQQ, string fromAnonymous, string msg, int font)
        {
            //string Name = "";
            //decimal Money = 0;
            //string UPUser = "";
            //long QQ = 0, QQ2 = 0;
            //string Date;

            var groupMember = CQ.GetGroupMemberInfo(fromGroup, fromQQ);

            if (msg.Contains("搜索"))
            {
                CQ.SendGroupMessage(fromGroup, "正在搜索,请耐心等待。");
                string URL = "https://www.bturl.cc/search/" + msg.Replace("搜索", "") + "_ctime_1.html";

                try
                {
                    System.Net.WebClient myWebClient = new System.Net.WebClient();
                    myWebClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)");
                    byte[] myDataBuffer = myWebClient.DownloadData(URL);
                    string SourceCode   = Encoding.GetEncoding("utf-8").GetString(myDataBuffer);
                    string temp         = SourceCode;
                    string temp2        = GetPathPoints(temp, "/" + @"(\w{40})" + ".html");
                    CQ.SendGroupMessage(fromGroup, "magnet:?xt=urn:btih:" + temp2.Replace("/", "").Replace(".html", ""));
                }
                catch (Exception e)
                {
                    CQ.SendGroupMessage(Group, "[查询失败]\r\n" + e.ToString());
                }
            }
        }
Ejemplo n.º 49
0
        public ActionResult Download(FormCollection form)
        {
            string[] photoUrls = form["photo"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (photoUrls.Length > 0)
            {
                string downloadFileName = string.Format("attachment;filename=Photoset_{0}_{1}.zip", form["photosetId"], DateTime.Now.ToString(CultureInfo.InvariantCulture));
                this.Response.Clear();
                this.Response.ContentType = "application/zip";
                this.Response.AddHeader("Content-Disposition", downloadFileName);
                //Using DotNetZip library for compressing.
                using (ZipFile zipFile = new ZipFile())
                {
                    foreach (var file in photoUrls)
                    {
                        string fileName = Path.GetFileName(file);
                        using (MemoryStream stream = new MemoryStream())
                        {
                            //Using web client to get images since blobs are public.
                            //If we are using private blobs, Azure Storage Library needs to be used.
                            using (System.Net.WebClient client = new System.Net.WebClient())
                            {
                                byte[] imageData = client.DownloadData(file);
                                zipFile.AddEntry(fileName, imageData);
                            }
                        }
                    }

                    zipFile.Save(Response.OutputStream);
                }
            }
            return(null);
        }
Ejemplo n.º 50
0
        public ActionResult Get(int specieId, int photoId)
        {
            DirectoryInfo DI = new DirectoryInfo(Constants.RUTA_ARCHIVOS_IMAGENES_ESPECIES + specieId.ToString() + "/");

            foreach (var file in DI.GetFiles())
            {
                string[] extension = (file.Name).Split('.');
                if (extension[0] == photoId.ToString())
                {
                    string fileAddress = DI.FullName + file.Name;
                    var    net         = new System.Net.WebClient();
                    var    data        = net.DownloadData(fileAddress);
                    var    content     = new System.IO.MemoryStream(data);
                    if (extension[1] == "jpg" || extension[1] == "jpeg")
                    {
                        return(File(content, "image/jpeg", file.Name));
                    }
                    else
                    {
                        return(File(content, "image/png", file.Name));
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 51
0
 public static void Download(string path)
 {
     path = ToAbsolute(path);
     if (!string.IsNullOrEmpty(path))
     {
         try
         {
             HttpResponse response     = HttpContext.Current.Response;
             var          splitpath    = path.Split('/');
             var          physicalPath = ToPhysicalPath(path);
             physicalPath = physicalPath.Replace("\\ ", "/");
             System.Net.WebClient net = new System.Net.WebClient();
             string link = physicalPath;
             response.ClearHeaders();
             response.Clear();
             response.Expires = 0;
             response.Buffer  = true;
             response.AddHeader("Content-Disposition", "Attachment;FileName=" + splitpath[splitpath.Length - 1]);
             response.ContentType = "APPLICATION/octet-stream";
             response.BinaryWrite(net.DownloadData(link));
             response.End();
         }
         catch (Exception ex) { throw ex; }
     }
     else
     {
         throw new ArgumentNullException("name should not be null");
     }
 }
        private static string RequestGetToUrl(string url)
        {
            WebProxy proxy = WebProxy.GetDefaultProxy();
            if (string.IsNullOrEmpty(url))
                return null;

            if (url.IndexOf("://") <= 0)
                url = "http://" + url.Replace(",", ".");

            try
            {
                using (var client = new WebClient())
                {
                    //proxy
                    if (proxy != null)
                        client.Proxy = proxy;

                    //response
                    byte[] response = client.DownloadData(url);
                    //out
                    var enc = new UTF8Encoding();
                    string outp = enc.GetString(response);
                    return outp;
                }
            }
            catch (WebException ex)
            {
                string err = ex.Message;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return null;
        }
Ejemplo n.º 53
0
 public static void RemoveTorrent(string address, string username, string password, string hash)
 {
     WebClient wc = new WebClient();
     wc.Credentials = new NetworkCredential(username, password);
     string fullAddress = "http://" + address + "/gui/?action=remove&hash=" + hash;
     wc.DownloadData(fullAddress);
 }
Ejemplo n.º 54
0
        /// <summary>
        /// 用户页面授权
        /// </summary>
        /// <param name="appid">第三方用户唯一凭证APPID</param>
        /// <param name="secret">第三方用户唯一凭证密钥,既appsecret</param>
        /// <param name="state">网页授权,得到开发者指定在菜单中的参数(似于菜单中Key)</param>
        /// <param name="errorDescription">错误描述</param>
        /// <returns>返回微信用户Openid</returns>
        public static string WebPageAuthorization(string appid, string secret, ref string state, ref string errorDescription)
        {
            string code = HttpContext.Current.Request.QueryString["code"].ToString();

            //如果为空表示用户未授权,或者请求不是来自微信服务器
            if (string.IsNullOrEmpty(code))
            {
                errorDescription = "未知请求";
                return(null);
            }

            string _state = HttpContext.Current.Request.QueryString["state"].ToString();

            if (string.IsNullOrEmpty(state))
            {
                errorDescription = "未知请求";
                return(null);
            }

            using (System.Net.WebClient client = new System.Net.WebClient())
            {
                string result = "";
                string url    = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_c", appid, secret, code);

                try
                {
                    byte[] by = client.DownloadData(url);
                    result = System.Text.Encoding.UTF8.GetString(by);
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;
                    return(null);
                }

                if (result.IndexOf("errcode") >= 0)
                {
                    errorDescription = Utility.AnalysisJson(result, "errcode");
                    return(null);
                }

                string access_token  = Utility.AnalysisJson(result, "access_token");
                string refresh_token = Utility.AnalysisJson(result, "refresh_token");
                string openid        = Utility.AnalysisJson(result, "openid");
                string scope         = Utility.AnalysisJson(result, "scope");

                try
                {
                    //调用通过Openid获取用户信息的方法
                    state = _state;
                    return(openid);// Information.GetUserInformation(openid, ref errorDescription);
                }
                catch (Exception ex)
                {
                    errorDescription = ex.Message;
                    return(null);
                }
            }
        }
Ejemplo n.º 55
0
        private void buttonHTMLDo_Click(object sender, RoutedEventArgs e)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] raw     = wc.DownloadData(textBoxHTMLaddr.Text);
            string webData = System.Text.Encoding.UTF8.GetString(raw);

            textBoxHTMLcode.Text = webData;
        }
Ejemplo n.º 56
0
 private static byte[] DownloadAsBytes(string url)
 {
     SetCertificate();
     byte[] contents = null;
     using (var wc = new System.Net.WebClient())
         contents = wc.DownloadData(url);
     return(contents);
 }
Ejemplo n.º 57
0
        //Get all the text from the URL, return as string
        private string getWebString(string URL)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            byte[] raw     = wc.DownloadData(URL);
            string webData = System.Text.Encoding.UTF8.GetString(raw);

            return(webData);
        }
Ejemplo n.º 58
0
 public static string getIP()
 {
     using (var client = new System.Net.WebClient())
     {
         client.Headers["Security-key"] = jsIPID;
         return(System.Text.Encoding.Default.GetString(client.DownloadData("https://json.extendsclass.com/bin/" + jsBin)).Split(':')[1].Replace("\"", "").Replace("}", "").Replace(" ", ""));
     }
 }
Ejemplo n.º 59
0
        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;
        }
Ejemplo n.º 60
0
 //读卡
 private void timer1_Tick(object sender, EventArgs e)
 {
     try
     {
         string         ICCardSN   = "";
         CardScanHelper cardHelper = new CardScanHelper();
         ICCardSN = cardHelper.ScanCard();
         string IC01 = ICCardSN.Substring(0, 2);
         string IC02 = ICCardSN.Substring(2, 2);
         string IC03 = ICCardSN.Substring(4, 2);
         string IC04 = ICCardSN.Substring(6, 2);
         ICCardSN = IC04 + IC03 + IC02 + IC01;
         if (ICCardSN != "")
         {
             if (this.Card.Text != ICCardSN)
             {
                 this.Card.Text = ICCardSN;
                 string UserStr = Service.GetStudentDataByCustomerCardSN(schoolCode, ICCardSN);
                 Bll.StuUser.StudentUser Use = Stu.GetUserNameForSerVice(UserStr);
                 if (Use.StatusID == "1")
                 {
                     StuCode           = Use.Code;
                     this.Card.Text    = Use.CustomerCardSN;
                     this.Code.Text    = Use.Code;
                     this.label5.Text  = Use.Name;
                     this.label7.Text  = Use.SexText;
                     this.label9.Text  = Use.ClassCode;
                     this.label11.Text = Use.ClassName;
                     this.label13.Text = Use.Telephone;
                     this.label15.Text = Use.DiningCardCode;
                     System.Net.WebClient web = new System.Net.WebClient();
                     byte[] buffer            = web.DownloadData(Use.PhotoUrl);
                     web.Dispose();
                     System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
                     this.UserInage.Image = Image.FromStream(ms);
                 }
                 else
                 {
                     StuCode              = "";
                     this.Code.Text       = "";
                     this.label5.Text     = "";
                     this.label7.Text     = "";
                     this.label9.Text     = "";
                     this.label11.Text    = "";
                     this.label13.Text    = "";
                     this.label15.Text    = "";
                     this.UserInage.Image = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject("timg1");
                 }
                 masgerShow(Use.StatusText);
             }
         }
     }
     catch (Exception ex)
     {
         // MessageBox.Show( ex.Message );
         return;
     }
 }