C # update address from Baidu image (update)

Source: Internet
Author: User
Tags key string

Feel change wallpaper is a troublesome thing, just recently in learning C #, casually do a thing, novice have a lot of insufficient hope forgive. (improved)

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Net;usingSystem.IO;usingSystem.Runtime.InteropServices;namespacegetwebhtml{classProgram {[DllImport ("user32.dll", EntryPoint ="SystemParametersInfo")]         Public Static extern intSystemParametersInfo (intUaction,intUparam,stringLpvparam,intfuWinIni);  Public Static ReadOnly string_path ="d:\\ouput.html";  Public Static int_width =1920x1080, _height = the; Static stringGetkeyword () {if(! File.exists ("KeyWord")) File.create ("KeyWord").            Close (); StreamReader SR=NewStreamReader ("KeyWord"); stringstr =""; stringdata ="";  while(str = Sr. ReadLine ())! =NULL) {Data+ = str +"\ n"; }            if(Data = ="") {Console.WriteLine ("No keywords"); Environment.exit (0); }            vardatas = data. Split ('\ n'); Sr.            Close (); returndatas[NewRandom (). Next (0, Datas. Length-1)]; }        Static string[] Getpicurl (stringSTRs) {            varDatas = STRs. Split (New string[] {"\ "Objurl\":"}, System.StringSplitOptions.RemoveEmptyEntries); intStart =0, end =0;  for(inti =1; I < datas. Length; i++) {Start= Datas[i]. IndexOf ("\"") +"\"".                Length; End= Datas[i]. IndexOf ("\","); Datas[i]= Datas[i]. Substring (Start, End-start); }            returndatas; }        Static voidMain (string[] args) {            if(! File.exists ("imgresolution")) File.create ("imgresolution").            Close (); StreamReader SR=NewStreamReader ("imgresolution"); stringmsg =Sr.            ReadLine (); if(Msg. Split (','). Length = =2) {_width= Int32.Parse (Msg. Split (',')[0]); _height= Int32.Parse (Msg. Split (',')[1]); } Sr.            Close (); Try{WebClient mywebclient=NewWebClient (); Mywebclient.credentials= CredentialCache.DefaultCredentials;//Gets or sets the network credentials that are used to authenticate requests to Internet resourcesbyte[] Pagedata= Mywebclient.downloaddata ("http://image.baidu.com/search/index?ct=&z=&tn=baiduimage&ipn=r&word="+ Getkeyword () +"&pn=0&ie=utf-8&oe=utf-8&cl=&lm=-1&fr=&se=&sme=&width="+ _width +"&height="+ _height);//download data from a specified Web site//string pagehtml = Encoding.Default.GetString (pagedata); //If you are using GB2312 to get a website page, use this sentence                stringpagehtml = Encoding.UTF8.GetString (pagedata);//If you are using UTF-8 to get a website page, use this sentence//Console.WriteLine (pagehtml);//Enter what you get in the console                /*if (!                                File.exists (_path)) file.create (_path); using (StreamWriter SW = new StreamWriter (_path, False))//writes the acquired content to the text {sw.                    Write (pagehtml); Sw.                Close (); }                */                if(! Directory.Exists ("c:\\users\\xiaoke\\pictures\\ダウンロードピクチャ\\")) Directory.CreateDirectory ("c:\\users\\xiaoke\\pictures\\ダウンロードピクチャ\\");  while(true)                {                    varSTRs =Getpicurl (pagehtml); Random Ram=NewRandom (); stringURL = Strs[ram. Next (1, STRs.                    Length)]; stringFileName ="c:\\users\\xiaoke\\pictures\\ダウンロードピクチャ\\"+ URL. Substring (URL. LastIndexOf ("/")); Try                    {                        if(!file.exists (FileName)) {file.create (fileName).                            Close ();                            Mywebclient.downloadfile (URL, fileName); SystemParametersInfo ( -,0, FileName,0x1); }                    }                    Catch(SystemException s) {Continue; }                     Break; }            }            Catch(WebException webEx) {Console.WriteLine (webEx.Message.ToString ()); }        }    }}

There are a few things to pay attention to, I used to write code also encountered, but did not make notes, so forget, but also try again, so it is important to do notes.

Start = Datas[i]. IndexOf ("\"") +"\"". Length;end = Datas[i]. IndexOf ("\",");d atas[i] = datas[i]. Substring (Start, End-Start);

So soSubstringThe function of () is the number of the delivery start and from start to end. It is worth noting that start is obtained by using the IndexOf () method, so the position of start is in the position of the first key string, so if we want to adjust the position to the last character of the string from the beginning of the string,
So I added the length of the string. Knowing the beginning and the end, thenstart position and quantity from start to endIt's good to make a difference.

Download Baidu image HTML Discovery Search image is stored in the "Objurl": Tag after the address, so here all the information is "Objurl": string to split.
< Span style= "color: #000000;" > after my observation found that the law of the Baidu website is as follows: 
http://image.baidu.com/ Search/index?ct=&z=&tn=baiduimage&ipn=r&word= "&pn=0&ie=utf-8&oe=utf-8&cl=&lm=-1&fr=&se=&sme= &width= &height= "+ High pixel

so you can query the desired result based on the keyword.

One more note is File.create (A stream is returned after the file is created, and the file is always occupied if the stream is not closed.

Do not care about Japanese, my computer is the Japanese system, in order not to let the style, I still use the Japanese name.


Root directory Receivedin the keyword fileTake keywords, line breaks separated, randomly select one. Resolution in the root meshrecorded in the imgresolution, not automatically obtained, because many computer resolution is difficult to match.

C # update address from Baidu image (update)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.