通用帮助类集合Shiny.Helper库的使用
一、说明
Shiny.Helper包主要集成了一些常用的帮助类,包括字符串处理,json处理,文件处理等
二、安装
nuget直接搜索安装即可
三、使用
1.经纬度计算距离
查看代码
using Shiny.Helper.Model;
using System;
namespace Shiny.Helper
{
///
/// 经纬度计算
///
public static class DistanceHelper
{
///
/// 根据一个给定经纬度的点和距离,进行附近地点查询
///
/// 经度
/// 纬度
/// 距离(单位:公里或千米)
/// 返回一个范围的4个点,最小纬度和纬度,最大经度和纬度
public static PositionModel FindNeighPosition(double longitude, double latitude, double distance)
{
//先计算查询点的经纬度范围
double r = 6378.137;//地球半径千米
double dis = distance;//千米距离
double dlng = 2 * Math.Asin(Math.Sin(dis / (2 * r)) / Math.Cos(latitude * Math.PI / 180));
dlng = dlng * 180 / Math.PI;//角度转为弧度
double dlat = dis / r;
dlat = dlat * 180 / Math.PI;
double minlat = latitude - dlat;
double maxlat = latitude + dlat;
double minlng = longitude - dlng;
double maxlng = longitude + dlng;
return new PositionModel
{
MinLat = minlat,
MaxLat = maxlat,
MinLng = minlng,
MaxLng = maxlng
};
}
///
/// 计算两点位置的距离,返回两点的距离,单位:公里或千米
/// 该公式为GOOGLE提供,误差小于0.2米
///
/// 第一点纬度
/// 第一点经度
/// 第二点纬度
/// 第二点经度
/// 返回两点的距离,单位:公里或千米
public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
{
//地球半径,单位米
double EARTH_RADIUS = 6378137;
double radLat1 = Rad(lat1);
double radLng1 = Rad(lng1);
double radLat2 = Rad(lat2);
double radLng2 = Rad(lng2);
double a = radLat1 - radLat2;
double b = radLng1 - radLng2;
double result = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2))) * EARTH_RADIUS;
return result / 1000;
}
///
/// 经纬度转化成弧度
///
///
///
private static double Rad(double d)
{
return (double)d * Math.PI / 180d;
}
}
}
2.加解密
查看代码
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Shiny.Helper
{
///
/// 加密解密
///
public static class EncryptHelper
{
#region DES加密解密
private const string desKey = "2wsxZSE$";
///
/// 加密
///
///
///
public static string DesEncrypt(string value, string key = desKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();//实例化加密类对象
byte[] arr_key = Encoding.UTF8.GetBytes(key.Substring(0, 8));//定义字节数组用来存放密钥 GetBytes方法用于将字符串中所有字节编码为一个字节序列
////!!!DES加密key位数只能是64位,即8字节
////注意这里用的编码用当前默认编码方式,不确定就用Default
byte[] arr_str = Encoding.UTF8.GetBytes(value);//定义字节数组存放要加密的字符串
MemoryStream ms = new MemoryStream();//实例化内存流对象
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(arr_key, arr_key), CryptoStreamMode.Write);//创建加密流对象,参数 内存流/初始化向量IV/加密流模式
cs.Write(arr_str, 0, arr_str.Length);//需加密字节数组/offset/length,此方法将length个字节从 arr_str 复制到当前流。0是偏移量offset,即从指定index开始复制。
cs.Close();
string str_des = Convert.ToBase64String(ms.ToArray());
return str_des;
}
///
/// 解密
///
///
///
public static string DesDecrypt(this string value, string key = desKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();//实例化加密类对象
byte[] arr_key = Encoding.UTF8.GetBytes(key.Substring(0, 8));//定义字节数组用来存放密钥 GetBytes方法用于将字符串中所有字节编码为一个字节序列
////!!!DES加密key位数只能是64位,即8字节
////注意这里用的编码用当前默认编码方式,不确定就用Default
//解密
var ms = new MemoryStream();
byte[] arr_des = Convert.FromBase64String(value);//注意这里仍要将密文作为base64字符串处理获得数组,否则报错
//byte[] arr_des = Encoding.UTF8.GetBytes(str_des);//不可行,将加密方法中ms的字符数组转为utf-8也不行
des = new DESCryptoServiceProvider();//解密方法定义加密对象
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(arr_key, arr_key), CryptoStreamMode.Write);//创建加密流对象,参数 内存流/初始化向量IV/加密流模式
cs = new CryptoStream(ms, des.CreateDecryptor(arr_key, arr_key), CryptoStreamMode.Write);
cs.Write(arr_des, 0, arr_des.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());//此处与加密前编码一致
}
#endregion
#region Base64加密解密
///
/// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
/// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ,
/// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的
/// 系統中而不同。
/// Base64加密
///
///
///
public static string Base64Encrypt(this string str)
{
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(encbuff);
}
///
/// Base64解密
///
///
///
public static string Base64Decrypt(this string str)
{
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
#endregion
#region SHA256加密解密
///
/// SHA256加密
///
///
///
public static string SHA256EncryptString(this string data)
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
byte[] hash = SHA256Managed.Create().ComputeHash(bytes);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
builder.Append(hash[i].ToString("x2"));
}
return builder.ToString();
}
///
/// SHA256加密
///
/// 待加密字符串
/// 加密数组
public static Byte[] SHA256EncryptByte(this string StrIn)
{
var sha256 = new SHA256Managed();
var Asc = new ASCIIEncoding();
var tmpByte = Asc.GetBytes(StrIn);
var EncryptBytes = sha256.ComputeHash(tmpByte);
sha256.Clear();
return EncryptBytes;
}
#endregion
}
}
3.文件处理
查看代码
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shiny.Helper
{
public class FileHelper : IDisposable
{
private bool _alreadyDispose = false;
#region 构造函数
public FileHelper()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
~FileHelper()
{
Dispose(); ;
}
protected virtual void Dispose(bool isDisposing)
{
if (_alreadyDispose) return;
_alreadyDispose = true;
}
#endregion
#region IDisposable 成员
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region 校验文件后缀名
public static bool CheckFileExtension(string fileExtension, string allowExtension)
{
string[] allowArr = UtilConvert.SplitToArray(allowExtension.ToLower(), '|');
if (allowArr.Where(p => p.Trim() == GetPostfixStr(fileExtension).ToLower()).Any())
{
return true;
}
else
{
return false;
}
}
#endregion
#region 取得文件后缀名
/****************************************
* 函数名称:GetPostfixStr
* 功能说明:取得文件后缀名
* 参 数:filename:文件名称
* 调用示列:
* string filename = "aaa.aspx";
* string s = EC.FileObj.GetPostfixStr(filename);
*****************************************/
///
/// 取后缀名
///
/// 文件名
/// .gif|.html格式
public static string GetPostfixStr(string filename)
{
int start = filename.LastIndexOf(".");
int length = filename.Length;
string postfix = filename[start..length];
return postfix;
}
#endregion
#region 写文件
/****************************************
* 函数名称:WriteFile
* 功能说明:写文件,会覆盖掉以前的内容
* 参 数:Path:文件路径,Strings:文本内容
* 调用示列:
* string Path = Server.MapPath("Default2.aspx");
* string Strings = "这是我写的内容啊";
* EC.FileObj.WriteFile(Path,Strings);
*****************************************/
///
/// 写文件
///
/// 文件路径
/// 文件内容
public static void WriteFile(string Path, string Strings)
{
if (!System.IO.File.Exists(Path))
{
FileStream f = System.IO.File.Create(Path);
f.Close();
}
StreamWriter f2 = new StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));
f2.Write(Strings);
f2.Close();
f2.Dispose();
}
///
/// 写文件
///
/// 文件路径
/// 文件内容
/// 编码格式
public static void WriteFile(string Path, string Strings, Encoding encode)
{
if (!System.IO.File.Exists(Path))
{
FileStream f = System.IO.File.Create(Path);
f.Close();
}
StreamWriter f2 = new StreamWriter(Path, false, encode);
f2.Write(Strings);
f2.Close();
f2.Dispose();
}
#endregion
#region 读文件
/****************************************
* 函数名称:ReadFile
* 功能说明:读取文本内容
* 参 数:Path:文件路径
* 调用示列:
* string Path = Server.MapPath("Default2.aspx");
* string s = EC.FileObj.ReadFile(Path);
*****************************************/
///
/// 读文件
///
/// 文件路径
///
public static string ReadFile(string Path)
{
string s;
if (!System.IO.File.Exists(Path))
return null;
else
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("utf-8"));
s = f2.ReadToEnd();
f2.Close();
f2.Dispose();
}
return s;
}
///
/// 读文件
///
/// 文件路径
/// 编码格式
///
public static string ReadFile(string Path, Encoding encode)
{
string s;
if (!System.IO.File.Exists(Path))
s = "不存在相应的目录";
else
{
StreamReader f2 = new StreamReader(Path, encode);
s = f2.ReadToEnd();
f2.Close();
f2.Dispose();
}
return s;
}
#endregion
#region 追加文件
/****************************************
* 函数名称:FileAdd
* 功能说明:追加文件内容
* 参 数:Path:文件路径,strings:内容
* 调用示列:
* string Path = Server.MapPath("Default2.aspx");
* string Strings = "新追加内容";
* EC.FileObj.FileAdd(Path, Strings);
*****************************************/
///
/// 追加文件
///
/// 文件路径
/// 内容
public static void FileAdd(string Path, string strings)
{
StreamWriter sw = File.AppendText(Path);
sw.Write(strings);
sw.Flush();
sw.Close();
}
#endregion
#region 拷贝文件
/****************************************
* 函数名称:FileCoppy
* 功能说明:拷贝文件
* 参 数:OrignFile:原始文件,NewFile:新文件路径
* 调用示列:
* string orignFile = Server.MapPath("Default2.aspx");
* string NewFile = Server.MapPath("Default3.aspx");
* EC.FileObj.FileCoppy(OrignFile, NewFile);
*****************************************/
///
/// 拷贝文件
///
/// 原始文件
/// 新文件路径
public static void FileCoppy(string orignFile, string NewFile)
{
File.Copy(orignFile, NewFile, true);
}
#endregion
#region 删除文件
/****************************************
* 函数名称:FileDel
* 功能说明:删除文件
* 参 数:Path:文件路径
* 调用示列:
* string Path = Server.MapPath("Default3.aspx");
* EC.FileObj.FileDel(Path);
*****************************************/
///
/// 删除文件
///
/// 路径
public static void FileDel(string Path)
{
File.Delete(Path);
}
#endregion
#region 移动文件
/****************************************
* 函数名称:FileMove
* 功能说明:移动文件
* 参 数:OrignFile:原始路径,NewFile:新文件路径
* 调用示列:
* string orignFile = Server.MapPath("../说明.txt");
* string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
* EC.FileObj.FileMove(OrignFile, NewFile);
*****************************************/
///
/// 移动文件
///
/// 原始路径
/// 新路径
public static void FileMove(string orignFile, string NewFile)
{
File.Move(orignFile, NewFile);
}
#endregion
#region 在当前目录下创建目录
/****************************************
* 函数名称:FolderCreate
* 功能说明:在当前目录下创建目录
* 参 数:OrignFolder:当前目录,NewFloder:新目录
* 调用示列:
* string orignFolder = Server.MapPath("test/");
* string NewFloder = "new";
* EC.FileObj.FolderCreate(OrignFolder, NewFloder);
*****************************************/
///
/// 在当前目录下创建目录
///
/// 当前目录
/// 新目录
public static void FolderCreate(string orignFolder, string NewFloder)
{
Directory.SetCurrentDirectory(orignFolder);
Directory.CreateDirectory(NewFloder);
}
#endregion
#region 递归删除文件夹目录及文件
/****************************************
* 函数名称:DeleteFolder
* 功能说明:递归删除文件夹目录及文件
* 参 数:dir:文件夹路径
* 调用示列:
* string dir = Server.MapPath("test/");
* EC.FileObj.DeleteFolder(dir);
*****************************************/
///
/// 递归删除文件夹目录及文件
///
///
///
public static void DeleteFolder(string dir)
{
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
File.Delete(d); //直接删除其中的文件
else
DeleteFolder(d); //递归删除子文件夹
}
Directory.Delete(dir); //删除已空文件夹
}
}
#endregion
#region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
/****************************************
* 函数名称:CopyDir
* 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
* 参 数:srcPath:原始路径,aimPath:目标文件夹
* 调用示列:
* string srcPath = Server.MapPath("test/");
* string aimPath = Server.MapPath("test1/");
* EC.FileObj.CopyDir(srcPath,aimPath);
*****************************************/
///
/// 指定文件夹下面的所有内容copy到目标文件夹下面
///
/// 原始路径
/// 目标文件夹
public static void CopyDir(string srcPath, string aimPath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if (aimPath[^1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判断目标目录是否存在如果不存在则新建之
if (!Directory.Exists(aimPath))
Directory.CreateDirectory(aimPath);
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
//string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(srcPath);
//遍历所有的文件和目录
foreach (string file in fileList)
{
//先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (Directory.Exists(file))
CopyDir(file, aimPath + Path.GetFileName(file));
//否则直接Copy文件
else
File.Copy(file, aimPath + Path.GetFileName(file), true);
}
}
catch (Exception ee)
{
throw new Exception(ee.ToString());
}
}
#endregion
}
}
4.json序列化
查看代码
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace Shiny.Helper
{
///
/// json序列化
///
public class JsonConvertHelper
{
///
/// body转json
///
///
///
public static string BodyToJson(HttpContext httpContext)
{
httpContext.Request.Body.Position = 0;
var reader = new StreamReader(httpContext.Request.Body);
try
{
return reader.ReadToEndAsync().Result;
}
catch (Exception ex)
{
return "";
}
}
///
/// 转Json
///
///
///
///
public static string ToJson(object result)
{
return JsonConvert.SerializeObject(result);
}
///
/// 转json忽略null值
///
///
///
public static string ToJsonIgnoreNull(object result)
{
JsonSerializerSettings jss = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
return JsonConvert.SerializeObject(result, jss);
}
///
/// 转换对象为JSON格式数据
///
/// 类
/// 对象
/// 字符格式的JSON数据
public static string GetJSON(object obj)
{
string result = string.Empty;
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
using MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
catch (Exception ex)
{
throw ex;
}
return result;
}
///
/// 转换List的数据为JSON格式
///
/// 类
/// 列表值
/// JSON格式数据
public static string JSON(List vals)
{
System.Text.StringBuilder st = new System.Text.StringBuilder();
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
foreach (T city in vals)
{
using MemoryStream ms = new MemoryStream();
s.WriteObject(ms, city);
st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
}
}
catch (Exception ex)
{
throw ex;
}
return st.ToString();
}
///
/// JSON格式字符转换为T类型的对象
///
///
///
///
public static T ParseFormByJson(string jsonStr)
{
using MemoryStream ms =
new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
///
/// JSON格式字符列表转换为lIST类型的对象
///
///
///
///
public static List ParseFormByJson(List jsonList)
{
List Tenity = new List();
foreach (var item in jsonList)
{
using MemoryStream ms =
new MemoryStream(System.Text.Encoding.UTF8.GetBytes(item));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
Tenity.Add((T)serializer.ReadObject(ms));
}
return Tenity;
}
}
}
5.网络帮助类
查看代码
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace ShinyLot.Common
{
///
/// 网络帮助
///
public class NetHelper
{
///
/// 获取本地IP地址信息
///
public static string GetAddressIP()
{
///获取本地的IP地址
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
}
}
return AddressIP;
}
///
/// 查看指定端口是否打开
///
///
///
public static bool CheckRemotePort(string url)
{
System.Uri urlInfo = new Uri(url, false);
bool result = false;
try
{
IPAddress ip = IPAddress.Parse(urlInfo.Host);
IPEndPoint point = new IPEndPoint(ip, urlInfo.Port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(point);
result = true;
}
catch (SocketException ex)
{
//10061 Connection is forcefully rejected.
if (ex.ErrorCode != 10061)
{
return false;
}
}
return result;
}
///
/// ping IP
///
///
///
public static bool PingIp(string url)
{
try
{
System.Uri urlInfo = new Uri(url, false);
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(urlInfo.Host, 120);//第一个参数为ip地址,第二个参数为ping的时间
if (reply.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
}
}
6.生成随机数
查看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shiny.Helper
{
///
/// 随机数
///
public class RandomHelper
{
///
/// 生成随机纯字母随机数
///
/// 生成长度
///
public static string GetLetter(int Length)
{
char[] Pattern = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
string result = "";
int n = Pattern.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < Length; i++)
{
int rnd = random.Next(0, n);
result += Pattern[rnd];
}
return result;
}
///
/// 生成随机字母和数字随机数
///
/// 生成长度
///
public static string GetLetterAndNumber(int Length)
{
char[] Pattern = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
string result = "";
int n = Pattern.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < Length; i++)
{
int rnd = random.Next(0, n);
result += Pattern[rnd];
}
return result;
}
///
/// 生成随机小写字母和数字随机数
///
/// 生成长度
///
public static string GetLetterAndNumberLower(int Length)
{
char[] Pattern = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
string result = "";
int n = Pattern.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < Length; i++)
{
int rnd = random.Next(0, n);
result += Pattern[rnd];
}
return result;
}
///
/// 生成随机字符串
///
/// 字符串的长度
///
public static string CreateRandomString(int length)
{
// 创建一个StringBuilder对象存储密码
StringBuilder sb = new StringBuilder();
//使用for循环把单个字符填充进StringBuilder对象里面变成14位密码字符串
for (int i = 0; i < length; i++)
{
Random random = new Random(Guid.NewGuid().GetHashCode());
//随机选择里面其中的一种字符生成
switch (random.Next(3))
{
case 0:
//调用生成生成随机数字的方法
sb.Append(CreateNum());
break;
case 1:
//调用生成生成随机小写字母的方法
sb.Append(CreateSmallAbc());
break;
case 2:
//调用生成生成随机大写字母的方法
sb.Append(CreateBigAbc());
break;
}
}
return sb.ToString();
}
///
/// 生成单个随机数字
///
public static int CreateNum()
{
Random random = new Random(Guid.NewGuid().GetHashCode());
int num = random.Next(10);
return num;
}
///
/// 生成单个大写随机字母
///
public static string CreateBigAbc()
{
//A-Z的 ASCII值为65-90
Random random = new Random(Guid.NewGuid().GetHashCode());
int num = random.Next(65, 91);
string abc = Convert.ToChar(num).ToString();
return abc;
}
///
/// 生成单个小写随机字母
///
public static string CreateSmallAbc()
{
//a-z的 ASCII值为97-122
Random random = new Random(Guid.NewGuid().GetHashCode());
int num = random.Next(97, 123);
string abc = Convert.ToChar(num).ToString();
return abc;
}
}
}
7.Unicode帮助类
查看代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Shiny.Helper
{
///
/// Unicode帮助类
///
public static class UnicodeHelper
{
///
/// 字符串转Unicode码
///
/// The to unicode.
/// Value.
public static string StringToUnicode(this string value)
{
byte[] bytes = Encoding.Unicode.GetBytes(value);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < bytes.Length; i += 2)
{
// 取两个字符,每个字符都是右对齐。
stringBuilder.AppendFormat("u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
}
return stringBuilder.ToString();
}
///
/// Unicode转字符串
///
/// The to string.
/// Unicode.
public static string UnicodeToString(this string unicode)
{
unicode = unicode.Replace("%", "\\");
return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
unicode, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
//string resultStr = "";
//string[] strList = unicode.Split('u');
//for (int i = 1; i < strList.Length; i++)
//{
// resultStr += (char)int.Parse(strList[i], System.Globalization.NumberStyles.HexNumber);
//}
//return resultStr;
}
}
}
8.类型转换
查看代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Shiny.Helper
{
///
/// 类型转换
///
public static class UtilConvert
{
#region 基本数据类型转换
public static string IntToString(int i)
{
return i.ToString();
}
///
/// object数组转Int数组
///
///
///
public static List ObjListToIntList(this object[] ids)
{
List list = new List();
foreach (var id in ids)
{
list.Add(id.ObjToInt());
}
return list;
}
///
/// 字符串转指定类型数组
///
///
///
///
public static T[] SplitToArray(string value, char split)
{
T[] arr = value.Split(new string[] { split.ToString() }, StringSplitOptions.RemoveEmptyEntries).CastSuper().ToArray();
return arr;
}
///
///
///
///
///
public static int ObjToInt(this object thisValue)
{
int reval = 0;
if (thisValue == null) return 0;
if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
public static string[] StringToArray(this string thisValue)
{
return thisValue.Split(",");
}
///
///
///
///
///
///
public static int ObjToInt(this object thisValue, int errorValue)
{
if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out int reval))
{
return reval;
}
return errorValue;
}
///
///
///
///
///
public static double ObjToMoney(this object thisValue)
{
if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out double reval))
{
return reval;
}
return 0;
}
///
///
///
///
///
///
public static double ObjToMoney(this object thisValue, double errorValue)
{
if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out double reval))
{
return reval;
}
return errorValue;
}
///
///
///
///
///
public static string ObjToString(this object thisValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return "";
}
///
///
///
///
///
///
public static string ObjToString(this object thisValue, string errorValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return errorValue;
}
///
///
///
///
///
public static decimal ObjToDecimal(this object thisValue)
{
if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out decimal reval))
{
return reval;
}
return 0;
}
///
///
///
///
///
///
public static decimal ObjToDecimal(this object thisValue, decimal errorValue)
{
if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out decimal reval))
{
return reval;
}
return errorValue;
}
///
///
///
///
///
public static DateTime ObjToDate(this object thisValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
reval = Convert.ToDateTime(thisValue);
}
return reval;
}
///
///
///
///
///
///
public static DateTime ObjToDate(this object thisValue, DateTime errorValue)
{
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out DateTime reval))
{
return reval;
}
return errorValue;
}
///
///
///
///
///
public static bool ObjToBool(this object thisValue)
{
bool reval = false;
if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
#endregion
#region 强制转换类型
///
/// 强制转换类型
///
///
///
///
public static IEnumerable CastSuper(this IEnumerable source)
{
foreach (object item in source)
{
yield return (TResult)Convert.ChangeType(item, typeof(TResult));
}
}
#endregion
#region 进制
///
/// 字符串转16进制字节数组
///
///
///
public static byte[] strToToHexByte(this string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
///
/// 将一个byte数组转换成16进制字符串
///
/// byte数组
/// 格式化的16进制字符串
public static string ByteArrayToHexString(this byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
{
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
}
return sb.ToString().ToUpper();
}
///
/// 十六进制转换到十进制
///
///
///
public static int Hex2Ten(this string hex)
{
int ten = 0;
for (int i = 0, j = hex.Length - 1; i < hex.Length; i++)
{
ten += HexChar2Value(hex.Substring(i, 1)) * ((int)Math.Pow(16, j));
j--;
}
return ten;
}
public static int HexChar2Value(string hexChar)
{
switch (hexChar)
{
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return Convert.ToInt32(hexChar);
case "a":
case "A":
return 10;
case "b":
case "B":
return 11;
case "c":
case "C":
return 12;
case "d":
case "D":
return 13;
case "e":
case "E":
return 14;
case "f":
case "F":
return 15;
default:
return 0;
}
}
#endregion
#region 流
///
/// 将 Stream 转成 byte[]
///
public static byte[] StreamToBytes(Stream stream)
{
//设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Close();
return bytes;
}
#endregion
#region 时间
///
/// 将c# DateTime时间格式转换为Unix时间戳格式
///
/// 时间
/// long
public static long ConvertDateTimeToLong(this DateTime time)
{
#pragma warning disable CS0618 // 类型或成员已过时
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
#pragma warning restore CS0618 // 类型或成员已过时
return (long)(time - startTime).TotalSeconds; // 相差秒数
}
public static int ConvertDateTimeToInt(this DateTime time)
{
#pragma warning disable CS0618 // 类型或成员已过时
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
#pragma warning restore CS0618 // 类型或成员已过时
return (int)(time - startTime).TotalSeconds; // 相差秒数
}
///
/// 将c# Unix时间戳格式转换为DateTime时间格式
///
///
///
///
public static DateTime StampToDatetime(this long TimeStamp, bool isMinSeconds = false)
{
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));//当地时区
//返回转换后的日期
if (isMinSeconds)
return startTime.AddMilliseconds(TimeStamp);
else
return startTime.AddSeconds(TimeStamp);
}
#endregion
#region 对字符串进行UrlEncode/UrlDecode
///
/// 对字符进行UrlEncode编码
/// string转Encoding格式
///
///
/// 编码格式
/// 是否输出大写字母
///
public static string UrlEncode(string text, Encoding encod, bool cap = true)
{
if (cap)
{
StringBuilder builder = new StringBuilder();
foreach (char c in text)
{
if (System.Web.HttpUtility.UrlEncode(c.ToString(), encod).Length > 1)
{
builder.Append(System.Web.HttpUtility.UrlEncode(c.ToString(), encod).ToUpper());
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
else
{
string encodString = System.Web.HttpUtility.UrlEncode(text, encod);
return encodString;
}
}
///
/// 对字符进行UrlDecode解码
/// Encoding转string格式
///
///
/// 编码格式
///
public static string UrlDecode(string encodString, Encoding encod)
{
string text = System.Web.HttpUtility.UrlDecode(encodString, encod);
return text;
}
#endregion
}
}