Reference page:
Http://www.yuanjiaocheng.net/webapi/test-webapi.html
Http://www.yuanjiaocheng.net/webapi/web-api-controller.html
Http://www.yuanjiaocheng.net/webapi/config-webapi.html
Http://www.yuanjiaocheng.net/webapi/web-api-route.html
Http://www.yuanjiaocheng.net/webapi/parameter-binding.html
Used to permanently object, what program is OK, depend on Newtonsoft. Used for JSON serialization and deserialization.
1 usingNewtonsoft.json;2 usingSystem;3 usingSystem.Collections.Generic;4 usingSystem.IO;5 usingSystem.Linq;6 usingSystem.Text;7 usingSystem.Threading.Tasks;8 9 namespaceConfighandlerTen { One Public classConfighandler<t> A whereT:class - { - Const stringSave_path ="jsonconfig/"; the /// <summary> - ///single-case mode - /// </summary> - StaticT config; + PrivateConfighandler () - { + A } at /// <summary> - ///Gets the save address, which defaults to the type name of the generic parameter T - /// </summary> - /// <returns></returns> - Private Static stringGetsavepath () - { in if(!directory.exists (save_path)) - { to directory.createdirectory (save_path); + } - return$"{save_path}{typeof (T). ToString ()}.json"; the } * /// <summary> $ ///Save ConfigurationPanax Notoginseng /// </summary> - Public Static voidSave (T _config) the { +Config =_config; A stringJSON =Jsonconvert.serializeobject (_config); the Try + { - using(varSW =NewStreamWriter (Getsavepath ())) $ { $ SW. WriteAsync (JSON); - } - the } - Catch(Exception)Wuyi { the Throw; - } Wu } - /// <summary> About ///Get configuration information $ /// </summary> - /// <returns></returns> - Public StaticT Load () - { A if(config = =NULL) + { the stringJSON =""; - Try $ { the using(varSR =NewStreamReader (Getsavepath ())) the { theJSON =Sr. ReadToEnd (); the if(JSON! ="") - { inConfig = jsonconvert.deserializeobject<t>(JSON); the } the Else About { theConfig =NULL; the } the } + } - Catch(Exception) the {BayiConfig =NULL; the } the } - returnconfig; - } the the } the the -}
View Code
Demo
usingConfighandler;usingConsoleApplication1;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication1{classProgram {Static voidMain (string[] args) {myconfig config=NewMyconfig (); Config=NewMyconfig (); Config.name="leiming"; Config. Age= -; Config. time=DateTime.Now; Confighandler<MyConfig>. Save (config); Config= confighandler<myconfig>. Load (); Console.WriteLine (config. ToString ()); Console.readkey (); } } classMyconfig { Public inthello{Get;Set;} Public stringName {Get;Set; } Public intAge {Get;Set; } PublicDateTime Time {Get;Set; } Public Override stringToString () {return$"name={name},age={age},time={time.toshortdatestring ()}"; } }}
View Code
C # Object instantiation saving a generic class with JSON makes it easy to save program settings