A long time, the common code will be a bit forgotten, or posted here for easy search!
1. Write the information to the file
//writes a string to the text voidWritetotext (stringmsg) { Try{msg= DateTime.Now.ToString ("YYYY-MM-DD Hh:mm:ss") +" : "+msg; stringFILEURL = HttpContext.Server.MapPath ("~/unionpaylog.txt"); System.IO.FileStream FS=NewSystem.IO.FileStream (FILEURL, System.IO.FileMode.Append); System.IO.StreamWriter SW=NewSystem.IO.StreamWriter (FS); Sw. WriteLine (msg); Sw. Close (); Fs. Close (); } Catch(Exception ex) {}}
2, save bitmap Picture object to local, or save picture byte array to local
/// <summary> ///save picture to local/// </summary> /// <param name= "BMP" ></param> /// <returns>return picture name</returns> Public Static stringSaveimagebybitmap (Bitmap bmp) {if(BMP = =NULL)return ""; stringImgname = Guid.NewGuid (). ToString () +". jpg"; stringLocalimgpath = Localimagefolder () +"\\"+imgname; using(BMP) {using(MemoryStream stream =NewMemoryStream ()) {BMP. Save (stream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] bytes =Stream. ToArray (); FileStream FS=NewFileStream (Localimgpath, FileMode.Create); BinaryWriter BW=NewBinaryWriter (FS); Bw. Write (bytes); Bw. Close (); Fs. Close (); } } returnimgname; } /// <summary> ///save picture byte array to local/// </summary> /// <param name= "bytes" ></param> /// <returns></returns> Public Static stringSaveimagebybytes (byte[] bytes) { stringImgname = Guid.NewGuid (). ToString () +". jpg"; stringLocalimgpath = Localimagefolder () +"\\"+imgname; FileStream FS=NewFileStream (Localimgpath, FileMode.Create); BinaryWriter BW=NewBinaryWriter (FS); Bw. Write (bytes); Bw. Close (); Fs. Close (); returnimgname; } /// <summary> ///get local picture path/// </summary> /// <returns></returns> Public Static stringLocalimagefolder () {stringDirpath = directory.getcurrentdirectory () +"\\tempImages"; if(!directory.exists (Dirpath)) {directory.createdirectory (Dirpath); } returnDirpath; }
View Code
3. Network request: Incoming JSON string, network request get return result
/// <summary> ///POST Request/// </summary> /// <param name= "url" >Request Server Interface</param> /// <param name= "paramstring" >parameter String</param> /// <param name= "Result" >The server returns the result string</param> /// <returns></returns> Public Static BOOLHttppostrequest (stringUrlstringParamstring,ref stringresult) {HttpWebRequest Request=NULL; //If you are sending an HTTPS request if(URL.) StartsWith ("HTTPS", StringComparison.OrdinalIgnoreCase)) { //servicepointmanager.servercertificatevalidationcallback = new Remotecertificatevalidationcallback ( CheckValidationResult);Request = WebRequest.Create (URL) asHttpWebRequest; //request. ProtocolVersion = Httpversion.version10; } Else{Request= WebRequest.Create (URL) asHttpWebRequest; } request. Method="POST"; Request. ContentType="Application/json;charset=utf-8"; //request. Headers.add ("Authorization", User.currentUser.token);Request. Headers.add ("accept-encoding","gzip"); //set proxy useragent and timeouts//request. useragent = useragent; //request. Timeout = timeout; //Send post Data byte[] data =Encoding.UTF8.GetBytes (paramstring); using(Stream stream =request. GetRequestStream ()) {stream. Write (data,0, data. Length); } HttpWebResponse response; Try{Response= Request. GetResponse () asHttpWebResponse; } Catch(Exception ex) {result="Error:"+Ex. Message; return false; } Stream stream2= Response. GetResponseStream ();//gets the string stream of the responseStreamReader sr =NewStreamReader (STREAM2);//Create a stream to read the streamresult = Sr. ReadToEnd ();//read the JSON string from the beginning to the endSr. Close (); Stream2. Close (); return true; }
View Code
Invocation Examples:
stringresult =""; stringParamsstr ="{\ "username\": \ "admin\", \ "password\": \ "123456\"}"; if(Httphelper.httppostrequest ("http://192.168.1.220:5188/user/login/in", Paramsstr,refresult)) {Console.WriteLine ("Success:"+result); } Else{Console.WriteLine ("Request fail:"+result); }
Parse JSON string as model object, reference Newtonsoft Library
Using Newtonsoft.json;
Using Newtonsoft.Json.Linq;
stringJsonstr ="{\ "code\": \ "0000\", \ "data\": {\ "name\": \ "xxx\", \ "age\": \ "xxx\"}, \ "msg\": \ "xxxxx\"}"; Jobject obj=Jobject.parse (JSONSTR); stringCode = obj["Code"]. ToString (); if(Code. Equals ("0000")) { stringDatastr = obj["Data"]. ToString (); Dictionary<string,string> datadict = jsonconvert.deserializeobject<dictionary<string,string>>(DATASTR); //...}
View Code
Documenting common Code Snippets in C #