通用帮助类集合SimpleTool库的使用
一、说明
SimpleTool包主要集成了一些常用的帮助类,包括字符串处理,json处理,文件处理等
github地址:https://github.com/zxzyjs/SimpleTool.git
gitee地址:
二、安装
nuget直接搜索安装即可
三、使用
1.经纬度计算距离
查看代码
using SimpleTool;
using System;
namespace SimpleSqlSugar
{
/// <summary>
/// 经纬度计算
/// </summary>
public static class DistanceHelper
{
/// <summary>
/// 根据一个给定经纬度的点和距离,进行附近地点查询
/// </summary>
/// <param name="longitude">经度</param>
/// <param name="latitude">纬度</param>
/// <param name="distance">距离(单位:公里或千米)</param>
/// <returns>返回一个范围的4个点,最小纬度和纬度,最大经度和纬度</returns>
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
};
}
/// <summary>
/// 计算两点位置的距离,返回两点的距离,单位:公里或千米
/// 该公式为GOOGLE提供,误差小于0.2米
/// </summary>
/// <param name="lat1">第一点纬度</param>
/// <param name="lng1">第一点经度</param>
/// <param name="lat2">第二点纬度</param>
/// <param name="lng2">第二点经度</param>
/// <returns>返回两点的距离,单位:公里或千米</returns>
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;
}
/// <summary>
/// 经纬度转化成弧度
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
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 SimpleSqlSugar
{
/// <summary>
/// 加密解密
/// </summary>
public static class EncryptHelper
{
#region DES加密解密
private const string desKey = "2wsxZSE$";
/// <summary>
/// 加密
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 解密
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
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加密解密
/// <summary>
/// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
/// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ,
/// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的
/// 系統中而不同。
/// Base64加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Encrypt(this string str)
{
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(encbuff);
}
/// <summary>
/// Base64解密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Decrypt(this string str)
{
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
#endregion
#region SHA256加密解密
/// <summary>
/// SHA256加密
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
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();
}
/// <summary>
/// SHA256加密
/// </summary>
/// <param name="StrIn">待加密字符串</param>
/// <returns>加密数组</returns>
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<string>(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);
*****************************************/
/// <summary>
/// 取后缀名
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>.gif|.html格式</returns>
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);
*****************************************/
/// <summary>
/// 写文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="Strings">文件内容</param>
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();
}
/// <summary>
/// 写文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="Strings">文件内容</param>
/// <param name="encode">编码格式</param>
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);
*****************************************/
/// <summary>
/// 读文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <returns></returns>
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;
}
/// <summary>
/// 读文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="encode">编码格式</param>
/// <returns></returns>
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);
*****************************************/
/// <summary>
/// 追加文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="strings">内容</param>
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);
*****************************************/
/// <summary>
/// 拷贝文件
/// </summary>
/// <param name="OrignFile">原始文件</param>
/// <param name="NewFile">新文件路径</param>
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);
*****************************************/
/// <summary>
/// 删除文件
/// </summary>
/// <param name="Path">路径</param>
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);
*****************************************/
/// <summary>
/// 移动文件
/// </summary>
/// <param name="OrignFile">原始路径</param>
/// <param name="NewFile">新路径</param>
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);
*****************************************/
/// <summary>
/// 在当前目录下创建目录
/// </summary>
/// <param name="OrignFolder">当前目录</param>
/// <param name="NewFloder">新目录</param>
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);
*****************************************/
/// <summary>
/// 递归删除文件夹目录及文件
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
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);
*****************************************/
/// <summary>
/// 指定文件夹下面的所有内容copy到目标文件夹下面
/// </summary>
/// <param name="srcPath">原始路径</param>
/// <param name="aimPath">目标文件夹</param>
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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace SimpleSqlSugar
{
/// <summary>
/// json序列化
/// </summary>
public class JsonConvertHelper
{
/// <summary>
/// 转Json
/// </summary>
/// <param name="code"></param>
/// <param name="result"></param>
/// <returns></returns>
public static string ToJson(object result)
{
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 转json忽略null值
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
public static string ToJsonIgnoreNull(object result)
{
JsonSerializerSettings jss = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
return JsonConvert.SerializeObject(result, jss);
}
/// <summary>
/// 转换对象为JSON格式数据
/// </summary>
/// <typeparam name="T">类</typeparam>
/// <param name="obj">对象</param>
/// <returns>字符格式的JSON数据</returns>
public static string GetJSON<T>(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;
}
/// <summary>
/// 转换List<T>的数据为JSON格式
/// </summary>
/// <typeparam name="T">类</typeparam>
/// <param name="vals">列表值</param>
/// <returns>JSON格式数据</returns>
public static string JSON<T>(List<T> 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();
}
/// <summary>
/// JSON格式字符转换为T类型的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static T ParseFormByJson<T>(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);
}
/// <summary>
/// JSON格式字符列表转换为lIST<T>类型的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static List<T> ParseFormByJson<T>(List<string> jsonList)
{
List<T> Tenity = new List<T>();
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
{
/// <summary>
/// 网络帮助
/// </summary>
public class NetHelper
{
/// <summary>
/// 获取本地IP地址信息
/// </summary>
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;
}
/// <summary>
/// 查看指定端口是否打开
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
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;
}
/// <summary>
/// ping IP
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
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 SimpleSqlSugar
{
/// <summary>
/// 随机数
/// </summary>
public class RandomHelper
{
/// <summary>
/// 生成随机纯字母随机数
/// </summary>
/// <param name="Length">生成长度</param>
/// <returns></returns>
public static string CreateLetter(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;
}
/// <summary>
/// 生成随机字母和数字随机数
/// </summary>
/// <param name="Length">生成长度</param>
/// <returns></returns>
public static string CreateLetterAndNumber(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;
}
/// <summary>
/// 生成随机小写字母和数字随机数
/// </summary>
/// <param name="Length">生成长度</param>
/// <returns></returns>
public static string CreateLetterAndNumberLower(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;
}
/// <summary>
/// 生成随机字符串
/// </summary>
/// <param name="length">字符串的长度</param>
/// <returns></returns>
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();
}
/// <summary>
/// 生成单个随机数字
/// </summary>
public static int CreateNum()
{
Random random = new Random(Guid.NewGuid().GetHashCode());
int num = random.Next(10);
return num;
}
/// <summary>
/// 生成指定长度的随机数字字符串
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string CreateNum(int length = 1)
{
Random random = new Random(Guid.NewGuid().GetHashCode());
var result = "";
for (int i = 0; i < length; i++)
{
result += random.Next(10);
}
return result;
}
/// <summary>
/// 生成单个大写随机字母
/// </summary>
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;
}
/// <summary>
/// 生成单个小写随机字母
/// </summary>
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
{
/// <summary>
/// Unicode帮助类
/// </summary>
public static class UnicodeHelper
{
/// <summary>
/// 字符串转Unicode码
/// </summary>
/// <returns>The to unicode.</returns>
/// <param name="value">Value.</param>
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();
}
/// <summary>
/// Unicode转字符串
/// </summary>
/// <returns>The to string.</returns>
/// <param name="unicode">Unicode.</param>
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 SimpleSqlSugar
{
/// <summary>
/// 类型转换
/// </summary>
public static class UtilConvert
{
#region 基本数据类型转换
public static string IntToString(int i)
{
return i.ToString();
}
/// <summary>
/// object数组转Int数组
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public static List<int> ObjListToIntList(this object[] ids)
{
List<int> list = new List<int>();
foreach (var id in ids)
{
list.Add(id.ObjToInt());
}
return list;
}
/// <summary>
/// 字符串转指定类型数组
/// </summary>
/// <param name="value"></param>
/// <param name="split"></param>
/// <returns></returns>
public static T[] SplitToArray<T>(string value, char split)
{
T[] arr = value.Split(new string[] { split.ToString() }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
return arr;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <returns></returns>
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(",");
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
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;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <returns></returns>
public static double ObjToMoney(this object thisValue)
{
if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out double reval))
{
return reval;
}
return 0;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
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;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <returns></returns>
public static string ObjToString(this object thisValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return "";
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
public static string ObjToString(this object thisValue, string errorValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return errorValue;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <returns></returns>
public static decimal ObjToDecimal(this object thisValue)
{
if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out decimal reval))
{
return reval;
}
return 0;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
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;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <returns></returns>
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;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <param name="errorValue"></param>
/// <returns></returns>
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;
}
/// <summary>
///
/// </summary>
/// <param name="thisValue"></param>
/// <returns></returns>
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 强制转换类型
/// <summary>
/// 强制转换类型
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
{
foreach (object item in source)
{
yield return (TResult)Convert.ChangeType(item, typeof(TResult));
}
}
#endregion
#region 进制
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 将一个byte数组转换成16进制字符串
/// </summary>
/// <param name="data">byte数组</param>
/// <returns>格式化的16进制字符串</returns>
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();
}
/// <summary>
/// 十六进制转换到十进制
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
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 流
/// <summary>
/// 将 Stream 转成 byte[]
/// </summary>
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 时间
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; // 相差秒数
}
#endregion
#region 对字符串进行UrlEncode/UrlDecode
/// <summary>
/// 对字符进行UrlEncode编码
/// string转Encoding格式
/// </summary>
/// <param name="text"></param>
/// <param name="encod">编码格式</param>
/// <param name="cap">是否输出大写字母</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 对字符进行UrlDecode解码
/// Encoding转string格式
/// </summary>
/// <param name="encodString"></param>
/// <param name="encod">编码格式</param>
/// <returns></returns>
public static string UrlDecode(string encodString, Encoding encod)
{
string text = System.Web.HttpUtility.UrlDecode(encodString, encod);
return text;
}
#endregion
}
}
9.GPS坐标转换
查看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleTool
{
/// <summary>
///坐标系转换帮助类
/// </summary>
/// WGS84:谷歌地图 OMS
/// 火星坐标系:高德地图 腾讯地图
/// 百度坐标系:百度地图
/// 7
/// 在地图学中,一般将坐标分为投影坐标和地理坐标。地理坐标和投影坐标的联系和区别对于一般的地图使用者而言可能并不需要掌握的非常清楚。通俗一点来说,地理坐标是一个球体的坐标,而投影坐标是一个平面的坐标。常用的GPS、百度地图、高德地图等都是采用的地理坐标。
//确定了地理坐标之后,常见的地图应用分别采用的都是什么坐标系呢?一般来说,国外的一些地图,都是采用WGS84坐标系,比如谷歌地图、OMS地图、Bing地图(非中国区域)等。而国内的地图,处于保密需求,大多采用火星坐标系,在WGS84的基础上作了一些偏移,如高德地图、腾讯地图等。而百度又在火星坐标系的基础上又作了一定偏移,生成了自己的百度坐标系。
//这些加密算法,一般是无法准确还原的,但是在小范围内的数据,可以通过一定的变换相互转化。具体的C#代码如下
public class GpsHelper
{
const double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
const double pi = 3.1415926535897932384626; // π
const double a = 6378245.0;// 长半轴
const double ee = 0.00669342162296594323; // 扁率
//火星转百度
public static GPSPoint Gcj02tobd09(GPSPoint HxCor)
{
double z = Math.Sqrt(HxCor.lng * HxCor.lng + HxCor.lat * HxCor.lat) + 0.00002 * Math.Sin(HxCor.lat * x_pi);
double theta = Math.Atan2(HxCor.lat, HxCor.lng) + 0.000003 * Math.Cos(HxCor.lng * x_pi);
GPSPoint BaiduCor;
BaiduCor.lng = z * Math.Cos(theta) + 0.0065;
BaiduCor.lat = z * Math.Sin(theta) + 0.006;
return BaiduCor;
}
//百度转火星
public static GPSPoint Bd09togcj02(GPSPoint Bd)
{
double x = Bd.lng - 0.0065;
double y = Bd.lat - 0.006;
double z = Math.Sqrt(x * x + y * y) - 0.00002 * Math.Sin(y * x_pi);
double theta = Math.Atan2(y, x) - .000003 * Math.Cos(x * x_pi);
GPSPoint hx;
hx.lng = z * Math.Cos(theta);
hx.lat = z * Math.Sin(theta);
return hx;
}
//WGS84转火星
public static GPSPoint Wgs84togcj02(GPSPoint wgs84)
{
if (OutOfChina(wgs84))
{
return wgs84;
}
double dlat = Transformlat(wgs84.lng - 105.0, wgs84.lat - 35.0);
double dlng = Transformlng(wgs84.lng - 105.0, wgs84.lat - 35.0);
double radlat = wgs84.lat / 180.0 * pi;
double magic = Math.Sin(radlat);
magic = 1 - ee * magic * magic;
double sqrtmagic = Math.Sqrt(magic);
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.Cos(radlat) * pi);
GPSPoint hx;
hx.lat = wgs84.lat + dlat;
hx.lng = wgs84.lng + dlng;
return hx;
}
//火星转84
public static GPSPoint Gcj02towgs84(GPSPoint hx)
{
if (OutOfChina(hx))
{
return hx;
}
double dlat = Transformlat(hx.lng - 105.0, hx.lat - 35.0);
double dlng = Transformlng(hx.lng - 105.0, hx.lat - 35.0);
double radlat = hx.lat / 180.0 * pi;
double magic = Math.Sin(radlat);
magic = 1 - ee * magic * magic;
double sqrtmagic = Math.Sqrt(magic);
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.Cos(radlat) * pi);
GPSPoint wgs84;
double mglat = hx.lat + dlat;
double mglng = hx.lng + dlng;
wgs84.lat = hx.lat * 2 - mglat;
wgs84.lng = hx.lng * 2 - mglng;
return wgs84;
}
//百度转84
public static GPSPoint Bd09towgs84(GPSPoint bd)
{
GPSPoint hx = Bd09togcj02(bd);
GPSPoint wgs84 = Gcj02towgs84(hx);
return wgs84;
}
//84转百度
public static GPSPoint Wgs84tobd09(GPSPoint wgs84)
{
GPSPoint hx = Wgs84togcj02(wgs84);
GPSPoint bd = Gcj02tobd09(hx);
return bd;
}
/*辅助函数*/
//判断是否在国内
private static Boolean OutOfChina(GPSPoint wgs84)
{
if (wgs84.lng < 72.004 || wgs84.lng > 137.8347)
{
return true;
}
if (wgs84.lat < 0.8293 || wgs84.lat > 55.8271)
{
return true;
}
return false;
}
/*辅助函数*/
//转换lat
private static double Transformlat(double lng, double lat)
{
double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat +
0.1 * lng * lat + 0.2 * Math.Sqrt(Math.Abs(lng));
ret += (20.0 * Math.Sin(6.0 * lng * pi) + 20.0 *
Math.Sin(2.0 * lng * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.Sin(lat * pi) + 40.0 *
Math.Sin(lat / 3.0 * pi)) * 2.0 / 3.0;
ret += (160.0 * Math.Sin(lat / 12.0 * pi) + 320 *
Math.Sin(lat * pi / 30.0)) * 2.0 / 3.0;
return ret;
}
/*辅助函数*/
//转换lng
private static double Transformlng(double lng, double lat)
{
double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng +
0.1 * lng * lat + 0.1 * Math.Sqrt(Math.Abs(lng));
ret += (20.0 * Math.Sin(6.0 * lng * pi) + 20.0 *
Math.Sin(2.0 * lng * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.Sin(lng * pi) + 40.0 *
Math.Sin(lng / 3.0 * pi)) * 2.0 / 3.0;
ret += (150.0 * Math.Sin(lng / 12.0 * pi) + 300.0 *
Math.Sin(lng / 30.0 * pi)) * 2.0 / 3.0;
return ret;
}
// 按类计算
public static GPSPoint Transform(GPSPoint corOld, string transType)
{
switch (transType)
{
case "百度转火星":
return GpsHelper.Bd09togcj02(corOld);
case "百度转84":
return GpsHelper.Bd09towgs84(corOld);
case "火星转84":
return GpsHelper.Gcj02towgs84(corOld);
case "84转火星":
return GpsHelper.Wgs84togcj02(corOld);
case "火星转百度":
return GpsHelper.Gcj02tobd09(corOld);
case "84转百度":
return GpsHelper.Wgs84tobd09(corOld);
default:
return corOld;
}
}
}
/// <summary>
/// 点位信息
/// </summary>
public struct GPSPoint
{
public double lng;
public double lat;
}
}
10.时间转换
查看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleSqlSugar
{
/// <summary>
/// 时间戳辅助类
/// </summary>
public static class TimeHelper
{
/// <summary>
/// 获取当前的时间戳
/// </summary>
/// <returns></returns>
public static long GetNowTimeStamp()
{
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
return (DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000;
}
/// <summary>
/// 获取当前毫秒时间戳
/// </summary>
/// <returns></returns>
public static long GetNowTimeStampMill()
{
DateTime dt1970 = new DateTime(1970, 1, 1);
DateTime current = DateTime.Now;
return (long)(current - dt1970).TotalMilliseconds;
}
/// <summary>
/// 将c# Unix时间戳格式转换为DateTime时间格式
/// </summary>
/// <param name="TimeStamp"></param>
/// <param name="isMinSeconds"></param>
/// <returns></returns>
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);
}
/// <summary>
/// 获取当前年的时间戳
/// </summary>
/// <returns></returns>
public static long GetYearTimeStamp()
{
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
DateTime yearStamp = new DateTime(DateTime.Now.Year, 1, 1);
return (yearStamp.Ticks - timeStamp.Ticks) / 10000000;
}
/// <summary>
/// 获取某一年的时间戳
/// </summary>
/// <param name="Year"></param>
/// <returns></returns>
public static long GetSomeYearTimeStamp(int Year)
{
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
DateTime yearStamp = new DateTime(Year, 1, 1);
return (yearStamp.Ticks - timeStamp.Ticks) / 10000000;
}
/// <summary>
/// 获取当前天的时间戳
/// </summary>
/// <returns></returns>
public static long GetDayStartTimeStamp()
{
DateTime timeStamp = new DateTime(1970, 1, 1); //得到1970年的时间戳
DateTime yearStamp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
return (yearStamp.Ticks - timeStamp.Ticks) / 10000000;
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">Unix时间戳格式</param>
/// <returns>C#格式时间</returns>
public static DateTime GetDateTimeFromUnix(this long timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
TimeSpan toNow = new TimeSpan(timeStamp * 10000000);
return dtStart.Add(toNow);
}
/// <summary>
/// 将c# DateTime时间格式转换为Unix时间戳格式
/// </summary>
/// <param name="time">时间</param>
/// <returns>long</returns>
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; // 相差秒数
}
/// <summary>
/// 计算时间差
/// </summary>
/// <param name="DateTime1"></param>
/// <param name="DateTime2"></param>
/// <returns></returns>
public static string GetDateDiff(this DateTime DateTime1, DateTime DateTime2)
{
string dateDiff = string.Empty;
TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
TimeSpan ts = ts1.Subtract(ts2).Duration();
dateDiff += ts.Days > 0 ? ts.Days.ToString() + "天" : string.Empty;
dateDiff += ts.Hours > 0 ? ts.Hours.ToString() + "小时" : string.Empty;
dateDiff += ts.Minutes > 0 ? ts.Minutes.ToString() + "分钟" : string.Empty;
dateDiff += ts.Seconds > 0 ? ts.Seconds.ToString() + "秒" : string.Empty;
return dateDiff;
}
}
}
11.Unicode帮助类
查看代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace SimpleSqlSugar
{
/// <summary>
/// Unicode帮助类
/// </summary>
public static class UnicodeHelper
{
/// <summary>
/// 字符串转Unicode码
/// </summary>
/// <returns>The to unicode.</returns>
/// <param name="value">Value.</param>
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();
}
/// <summary>
/// Unicode转字符串
/// </summary>
/// <returns>The to string.</returns>
/// <param name="unicode">Unicode.</param>
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;
}
}
}
12.字符串帮助类
查看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleTool
{
/// <summary>
/// 字符串帮助类
/// </summary>
public static class StringHelper
{
/// <summary>
/// 首字母小写写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string FirstCharToLower(this string input)
{
if (String.IsNullOrEmpty(input))
return input;
string str = input.First().ToString().ToLower() + input.Substring(1);
return str;
}
/// <summary>
/// 首字母大写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string FirstCharToUpper(this string input)
{
if (String.IsNullOrEmpty(input))
return input;
string str = input.First().ToString().ToUpper() + input.Substring(1);
return str;
}
}
}
本文来自博客园,作者:HuTiger,转载请注明原文链接:https://www.cnblogs.com/huguodong/p/16400206.html,欢迎加入qq群927460240学习讨论
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」