写入创建txt文件
/// <summary> /// 生成文件 /// </summary> /// <param name="content">文件内容</param> public void CreatePage(string content, string filename) { try { if (!System.IO.Directory.Exists(filename.Substring(0, filename.LastIndexOf(‘/‘)))) { System.IO.Directory.CreateDirectory(filename.Substring(0, filename.LastIndexOf(‘/‘))); } FileStream fs = new FileStream(filename, FileMode.Create); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312")); sw.WriteLine(content); sw.Flush(); sw.Close(); bool result =if (result == false) { //发送文件失败 HttpContext.Current.Response.Write(filename + "发送失败"); } } catch (Exception ex) { HttpContext.Current.Response.Write(filename + ex.ToString()); } }
如果txt文件存在 写入文件
/// <summary> /// 写入文件 /// </summary> /// <param name="dizhi">写入地址</param> /// <param name="content">写入内容</param> public string WriteToFile(string dizhi, string content, bool isfugai) { string message = string.Empty; try { System.IO.FileInfo file = new System.IO.FileInfo(dizhi); //独占方式,因为文件只能由一个进程写入. System.IO.StreamWriter writer1 = null; writer1 = new System.IO.StreamWriter(file.FullName, isfugai);//文件不存在就创建 writer1.WriteLine(content); writer1.Close(); } catch { message = "已有人在同步数据请稍后同步"; } return message; }
写入txt文件
/// <summary> /// 获取微信令牌 /// </summary> /// <returns></returns> public string Getjsapi_tiket(string token) { FileStream fs1 = new FileStream("d:/webwz/m/wxtest/jsapi_tiket.txt", FileMode.Open); StreamReader sr = new StreamReader(fs1, Encoding.GetEncoding("GBK")); string AccToken = sr.ReadToEnd(); sr.Close(); fs1.Close(); getqianming at = JsonDeserialize<getqianming>(AccToken); if (DateTime.Now > Convert.ToDateTime(at.expires_in)) { //当前时间大于过期时间就重新获取jsapi_tiket令牌 //获取到微信返回的json数据 string ticket = GetPage("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi"); getqianming jstiket = JsonDeserialize<getqianming>(ticket); string jstik = jstiket.ticket; //将返回的数据写入到文件内 //{"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u6THi9cRoPFeaORrzm-Klx3NMKJVnp0u-oa3DL920A6AsEBxM2DZTRCAkXlS5yoIkg","expires_in":7200} //E:/work1/wxtest/jsapi_tiket.txt WriteToFile("d:/webwz/m/wxtest/jsapi_tiket.txt", "{\"errcode\":" + jstiket.errcode + ",\"errmsg\":\"" + jstiket.errmsg + "\",\"ticket\":\"" + jstik + "\",\"expires_in\":\"" + DateTime.Now.AddSeconds(Convert.ToInt32(jstiket.expires_in) - 300) + "\"}", false); return jstik; } else { //未过期就继续使用从文档中获取的AccessToken令牌 return at.ticket; } }
json反序列化的
/// <summary> /// json格式转化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> public T JsonDeserialize<T>(string jsonString) { System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; }
时间: 2024-10-13 13:07:51