一、說明
Shiny.Helper包主要集成了一些常用的幫助類,包括字符串處理,json處理,文件處理等
二、安裝
nuget直接搜索安裝即可
三、使用
1.經緯度計算距離
查看代碼
using Shiny.Helper.Model;
using System;
namespace Shiny.Helper
{
/// <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 Shiny.Helper
{
/// <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 Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace Shiny.Helper
{
/// <summary>
/// json序列化
/// </summary>
public class JsonConvertHelper
{
/// <summary>
/// body轉json
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
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 "";
}
}
/// <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 Shiny.Helper
{
/// <summary>
/// 隨機數
/// </summary>
public class RandomHelper
{
/// <summary>
/// 生成隨機純字母隨機數
/// </summary>
/// <param name="Length">生成長度</param>
/// <returns></returns>
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;
}
/// <summary>
/// 生成隨機字母和數字隨機數
/// </summary>
/// <param name="Length">生成長度</param>
/// <returns></returns>
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;
}
/// <summary>
/// 生成隨機小寫字母和數字隨機數
/// </summary>
/// <param name="Length">生成長度</param>
/// <returns></returns>
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;
}
/// <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>
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 Shiny.Helper
{
/// <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 時間
/// <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; // 相差秒數
}
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; // 相差秒數
}
/// <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);
}
#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
}
}