C#高级编程 - 小鸟系列之常用方法

这里汇总下C#的常用方法,后续会不断更新

序列化

添加引用Newtonsoft.Json.dll

public static string JSONSerializeObject(object oObject)
{
    return JsonConvert.SerializeObject(oObject);
}

反序列化

添加引用Newtonsoft.Json.dll

public static object JSONDeserializeObject<T>(string value)
{
    return JsonConvert.DeserializeObject<T>(value, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
}

获取时间戳

public static long getTimeStamp(this DateTime dt)
{
    var start = new DateTime(1970, 1, 1, 0, 0, 0, dt.Kind);
    return Convert.ToInt64((dt - start).TotalSeconds);
}

将DataTable转换成对象(List<T>)

public static List<T> toList<T>(this DataTable dt) where T : class, new()
{
    List<T> oList = new List<T>();
    Type type = typeof(T);
    string tempName = string.Empty;
    foreach (DataRow dr in dt.Rows)
    {
        T t = new T();
        PropertyInfo[] propertys = t.GetType().GetProperties();
        foreach (PropertyInfo pi in propertys)
        {
            tempName = pi.Name;
            if (dt.Columns.Contains(tempName))
            {
                if (!pi.CanWrite) continue;
                object value = dr[tempName];
                if (value != DBNull.Value)
                    pi.SetValue(t, value, null);
            }
        }
        oList.Add(t);
    }
    return oList;
}
调用: 
List<Persion> _persion = dtList.toList<Persion>();

SHA1加密

public static string EncryptToSHA1(string str)
{
    SHA1 sha1 = new SHA1CryptoServiceProvider();
    byte[] bytes_sha1_in = UTF8Encoding.Default.GetBytes(str);
    byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
    string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
    str_sha1_out = str_sha1_out.Replace("-", "");
    return str_sha1_out;
}

SHA512加密

public static string EncryptToSHA512(string str)
{
    var sha = new SHA512Managed();

    var bytes = Encoding.UTF8.GetBytes(str);
    var encryptedBytes = sha.ComputeHash(bytes);
    var encryptedInput = BitConverter.ToString(encryptedBytes);
    encryptedInput = encryptedInput.Replace("-", "");

    return encryptedInput;
}
模拟Http发送Post或Get请求
public static string SendRequest(string requestUrl, string data, 
string contentType = "application/json", string requestMethod = WebRequestMethods.Http.Post, int connectionLimit = 100)
{
    HttpWebRequest httpWebRequest = null;
    string returnData = "";
    try
    {
        httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
        httpWebRequest.Method = requestMethod;
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Proxy = null;
        httpWebRequest.KeepAlive = false;
        httpWebRequest.Timeout = 1000 * 25;
        httpWebRequest.Headers.Add("Origin", "SIS API");
        httpWebRequest.ServicePoint.ConnectionLimit = connectionLimit;
        httpWebRequest.ServicePoint.UseNagleAlgorithm = false;
        httpWebRequest.ServicePoint.ConnectionLimit = 100;
        httpWebRequest.AllowWriteStreamBuffering = false;
        httpWebRequest.Accept = "application/json";

        byte[] dataArray = Encoding.UTF8.GetBytes(data);
        httpWebRequest.ContentLength = dataArray.Length;

        using (Stream requestStream = httpWebRequest.GetRequestStream())
        {
            requestStream.Write(dataArray, 0, dataArray.Length);
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            returnData = streamReader.ReadToEnd();

            streamReader.Close();
            httpWebResponse.Close();
        }

        httpWebRequest.Abort();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (httpWebRequest != null)
        {
            httpWebRequest.Abort();
            httpWebRequest = null;
        }
    }

    return returnData;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值