• C#开发中常用的小功能


    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Net;
    using System.Reflection;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Security.Cryptography;
    using System.Text;
    using System.Xml.Serialization;
    
    namespace KLS.Common
    {
        /// <summary>
        /// 对象的序列化和反序列化工具类
        /// </summary>
        public static class Tools
        {
            // 序列化:对象 -> Xml文本
            public static string SerializeToXmlString(object obj)
            {
                StringBuilder buffer = new StringBuilder();
                using (TextWriter writer = new StringWriter(buffer))
                {
                    XmlSerializer xmlSrlzer = new XmlSerializer(obj.GetType());
                    xmlSrlzer.Serialize(writer, obj);
                }
                return buffer.ToString();
            }
    
            // 反序列化:Xml文本 -> 对象
            public static TClass DeserializeFromXmlString<TClass>(string xml) where TClass : new()
            {
                try
                {
                    using (StringReader reader = new StringReader(xml))
                    {
                        XmlSerializer xmlSrlzer = new XmlSerializer(typeof(TClass));
                        return (TClass)xmlSrlzer.Deserialize(reader);
                    }
                }
                catch (Exception ex)
                {
                    ex.Source = ex.Source;
                    return new TClass();
                }
            }
    
            // 序列化:对象 -> Xml文件
            public static void SerializeToXmlFile(object obj, string file)
            {
                using (TextWriter writer = new StreamWriter(file))
                {
                    XmlSerializer serializer = new XmlSerializer(obj.GetType());
                    serializer.Serialize(writer, obj);
                }
            }
    
            // 反序列化:Xml文件 -> 对象
            public static TClass DeserializeFromXmlFile<TClass>(string file) where TClass : new()
            {
                if (!File.Exists(file))
                {
                    return new TClass();
                }
                try
                {
                    using (FileStream reader = new FileStream(file, FileMode.Open))
                    {
                        XmlSerializer xmlSrlzer = new XmlSerializer(typeof(TClass));
                        return (TClass)xmlSrlzer.Deserialize(reader);
                    }
                }
                catch (Exception ex)
                {
                    ex.Source = ex.Source;
                    return new TClass();
                }
            }
    
            /// <summary>
            /// DES对称加密解密:bytes
            /// </summary>
            /// <param name="encrypt">true: 加密;false: 解密</param>
            public static byte[] EncryptDES(byte[] input, byte[] key, byte[] iv, bool encrypt = true)
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider() { Key = key, IV = iv };
                ICryptoTransform transform = encrypt ? des.CreateEncryptor() : des.CreateDecryptor();
                using (MemoryStream ms = new MemoryStream())
                {
                    CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                    cs.Write(input, 0, input.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                    return ms.ToArray();
                }
            }
    
            /// <summary>
            /// DES对称加密解密:string <-> Base64String
            /// </summary>
            /// <param name="encrypt">true: 加密;false: 解密</param>
            public static string EncryptDES(string text, byte[] key, byte[] iv, bool encrypt = true)
            {
                try
                {
                    byte[] input = encrypt ? Encoding.UTF8.GetBytes(text) : Convert.FromBase64String(text);
                    byte[] output = EncryptDES(input, key, iv, encrypt);
                    string result = encrypt ? Convert.ToBase64String(output) : Encoding.UTF8.GetString(output);
                    return result;
                }
                catch (Exception ex)
                {
                    ex.Source = ex.Source;
                    return "";
                }
            }
    
            /// <summary>
            /// DES对称加密解密:string <-> Base64String
            /// </summary>
            /// <param name="encrypt">true: 加密;false: 解密</param>
            public static string EncryptDES(string text, string skey, string siv, bool encrypt = true)
            {
                try
                {
                    byte[] key = Encoding.UTF8.GetBytes(skey.Substring(0, 8));
                    byte[] iv = Encoding.UTF8.GetBytes(siv.Substring(0, 8));
                    byte[] input = encrypt ? Encoding.UTF8.GetBytes(text) : Convert.FromBase64String(text);
                    byte[] output = EncryptDES(input, key, iv, encrypt);
                    string result = encrypt ? Convert.ToBase64String(output) : Encoding.UTF8.GetString(output);
                    return result;
                }
                catch (Exception ex)
                {
                    ex.Source = ex.Source;
                    return "";
                }
            }
    
            public static string EncryptMD5(string text)
            {
                MD5 md5 = MD5.Create();
                byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
                return Convert.ToBase64String(bytes);
            }
    
            /// <summary>
            /// 设置对象属性的特性值,可用于动态修改PropertyGrid的Browsable特性
            /// </summary>
            public static void SetPropertyAttribute(object obj, string propertyName, Type attrType, string attrField, object value)
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
                Attribute attr = props[propertyName].Attributes[attrType];
                FieldInfo field = attrType.GetField(attrField, BindingFlags.Instance | BindingFlags.NonPublic);
                field.SetValue(attr, value);
            }
    
            /// <summary>
            /// 给属性设置DefaultValueAttribute配置的值
            /// </summary>
            public static void SetDefaultValueOfAttribute(object obj)
            {
                Type attrType = typeof(DefaultValueAttribute);
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
                foreach (PropertyDescriptor prop in props)
                {
                    DefaultValueAttribute attr = (DefaultValueAttribute)prop.Attributes[attrType];
                    if (attr != null)
                    {
                        prop.SetValue(obj, attr.Value);
                    }
                }
            }
    
            public static string GetEnumDescription(this Enum item)
            {
                string result = item.ToString();
                FieldInfo field = item.GetType().GetField(result);
                DescriptionAttribute description = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (description != null) result = description.Description;
                return result;
            }
    
            public static void RunCmd(string cmd)
            {
                ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
                startInfo.CreateNoWindow = true;
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardInput = true;
                startInfo.RedirectStandardOutput = true;                          //win7上必须要设置,否则命令行没有成功执行;在win10上却可以不用设置
                Process process = new Process() { StartInfo = startInfo };
                process.Start();
                process.StandardInput.WriteLine(cmd);
                process.StandardInput.WriteLine("exit");
                process.WaitForExit();
            }
    
            public static long LinearCalc(long x, long X1, long X2, long Y1, long Y2)
            {
                if (x <= X1) return Y1;
                if (x >= X2) return Y2;
                return ((int)x - X1) * (Y2 - Y1) / (X2 - X1) + Y1;
            }
    
            /// <summary>
            /// HttpGET操作
            /// </summary>
            /// <param name="contentType">image/jpeg, application/json</param>
            public static string HttpGetJson(string url)
            {
                string retString = string.Empty;
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method = "GET";
                    request.ContentType = "application/json";
    
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream myResponseStream = response.GetResponseStream())
                        {
                            using (StreamReader streamReader = new StreamReader(myResponseStream))
                            {
                                retString = streamReader.ReadToEnd();
                                streamReader.Close();
                            }
                            myResponseStream.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.Source = ex.Source;
                }
                return retString;
            }
    
            /// <summary>
            /// HttpGET操作
            /// </summary>
            public static Image HttpGetImg(string url)
            {
                Image image = null;
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method = "GET";
                    request.ContentType = "image/jpeg";
    
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            image = Image.FromStream(stream);
                            stream.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.Source = ex.Source;
                }
                return image;
            }
    
            public static string HttpPost(string Url, string postDataStr, string contentType, out bool isOK)
            {
                string retString = string.Empty;
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                    request.Method = "POST";
                    request.ContentType = contentType;
                    request.Timeout = 600000;
                    request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                    using (Stream requestStream = request.GetRequestStream())
                    {
                        using (StreamWriter streamWriter = new StreamWriter(requestStream))
                        {
                            streamWriter.Write(postDataStr);
                            streamWriter.Close();
                        }
                    }
    
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            using (StreamReader streamReader = new StreamReader(responseStream))
                            {
                                retString = streamReader.ReadToEnd();
                                streamReader.Close();
                                responseStream.Close();
                            }
                        }
                    }
    
                    isOK = true;
                }
                catch (Exception ex)
                {
                    if (ex.GetType() == typeof(WebException))//捕获400错误
                    {
                        var response = ((WebException)ex).Response;
                        Stream responseStream = response.GetResponseStream();
                        StreamReader streamReader = new StreamReader(responseStream);
                        retString = streamReader.ReadToEnd();
                        streamReader.Close();
                        responseStream.Close();
                    }
                    else
                    {
                        retString = ex.ToString();
                    }
                    isOK = false;
                }
    
                return retString;
            }
        }
    }
  • 相关阅读:
    随意给一组数,找出满足一下条件的a[i],a[i]左边的数小于等于a[i],a[i]右边的数大于等于a[i]
    SVN
    四种进程或线程同步互斥的控制方法
    二叉树转双向链表
    最大连续子序列和
    找出一个字符串中第一个只出现一次的字符
    清除浮动的那些事
    jQuery中ready与load事件的区别
    css 经典布局之圣杯布局(左右固定,中间自适应)
    window.name + iframe跨域实例
  • 原文地址:https://www.cnblogs.com/zhuyingchun/p/13934915.html
Copyright © 2020-2023  润新知