记录C#常用的代码片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了记录C#常用的代码片段相关的知识,希望对你有一定的参考价值。

  时间一久,常用的代码会有点忘记,还是贴在这里方便查找!

1、将信息写入文件中

//将字符串写入到文本中
        void writeToText(string msg)
        {
            try
            {
                msg = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " : " + msg;
                string fileUrl = HttpContext.Server.MapPath("~/unionpayLog.txt");
                
                System.IO.FileStream fs = new System.IO.FileStream(fileUrl, System.IO.FileMode.Append);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
                sw.WriteLine(msg);
                sw.Close();
                fs.Close();
            }
            catch (Exception ex) { }
        }

 

2、保存Bitmap图片对象到本地, 或者保存图片字节数组到本地

技术分享
/// <summary>
        /// 保存图片到本地
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns>返回图片名字</returns>
        public static string SaveImageByBitmap(Bitmap bmp)
        {
            if (bmp == null) return "";

            string imgName = Guid.NewGuid().ToString() + ".jpg";
            string localImgPath = LocalImageFolder() + "\\" + imgName;

            using (bmp)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] bytes = stream.ToArray();

                    FileStream fs = new FileStream(localImgPath, FileMode.Create);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(bytes);
                    bw.Close();
                    fs.Close();
                }
            }

            return imgName;
        }

        /// <summary>
        /// 保存图片字节数组到本地
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string SaveImageByBytes(byte[] bytes)
        {
            string imgName = Guid.NewGuid().ToString() + ".jpg";
            string localImgPath = LocalImageFolder() + "\\" + imgName;

            FileStream fs = new FileStream(localImgPath, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(bytes);
            bw.Close();
            fs.Close();
            return imgName;
        }

        /// <summary>
        /// 获取本地图片路径
        /// </summary>
        /// <returns></returns>
        public static string LocalImageFolder()
        {
            string dirPath = Directory.GetCurrentDirectory() + "\\tempImages";

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            return dirPath;
        }
View Code

 

3、网络请求: 传入json字符串,网络请求获得返回结果

技术分享
/// <summary>
        /// post请求
        /// </summary>
        /// <param name="url">请求服务器接口</param>
        /// <param name="paramString">参数字符串</param>
        /// <param name="result">服务器返回结果字符串</param>
        /// <returns></returns>
        public static bool HttpPostRequest(string url, string paramString, ref string result)
        {
            HttpWebRequest request = null;
           
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                //request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            //request.Headers.Add("Authorization", User.currentUser.token);
            request.Headers.Add("Accept-Encoding", "gzip");

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout; 

            //发送POST数据  
            byte[] data = Encoding.UTF8.GetBytes(paramString);
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            HttpWebResponse response;

            try
            {
                 response = request.GetResponse() as HttpWebResponse;
            }
            catch (Exception ex)
            {
                result = "error: " + ex.Message;
                return false;
            }
            
            Stream stream2 = response.GetResponseStream();   //获取响应的字符串流
            StreamReader sr = new StreamReader(stream2); //创建一个stream读取流
            result = sr.ReadToEnd();   //从头读到尾,读取json字符串
            sr.Close();
            stream2.Close();

            return true;
        }
View Code

调用举例:

string result = "";
            string paramsStr = "{\"userName\":\"admin\", \"password\":\"123456\"}";

            if (HttpHelper.HttpPostRequest("http://192.168.1.220:5188/user/login/in", paramsStr, ref result))
            {
                Console.WriteLine("success:" + result);
            }
            else
            {
                Console.WriteLine("请求fail:" + result);
            }

 

解析json字符串为模型对象,引用Newtonsoft库

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

 

技术分享
string jsonStr = "{\"code\":\"0000\", \"data\":{\"name\":\"xxx\", \"age\":\"xxx\"}, \"msg\":\"xxxxx\"}";
            JObject obj = JObject.Parse(jsonStr);
            string code = obj["code"].ToString();

            if (code.Equals("0000"))
            {
                string dataStr = obj["data"].ToString();
                Dictionary<string, string> dataDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataStr);
                //...
            }
View Code

 


以上是关于记录C#常用的代码片段的主要内容,如果未能解决你的问题,请参考以下文章

提效小技巧——记录那些不常用的代码片段

C#程序员经常用到的10个实用代码片段 - 操作系统

常用python日期日志获取内容循环的代码片段

c#代码片段快速构建代码

此 Canon SDK C++ 代码片段的等效 C# 代码是啥?

C# 最有用的(自定义)代码片段是啥? [关闭]