Open androllen opened 4 years ago
C# 对称加密
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Program
{
public class EncryptHelper
{
public EncryptHelper()
{
this.mobjCryptoService = new RijndaelManaged();
this.Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
}
private byte[] GetLegalKey()
{
string text = this.Key;
this.mobjCryptoService.GenerateKey();
byte[] key = this.mobjCryptoService.Key;
int num = key.Length;
if (text.Length > num)
{
text = text.Substring(0, num);
}
else if (text.Length < num)
{
text = text.PadRight(num, ' ');
}
return Encoding.ASCII.GetBytes(text);
}
private byte[] GetLegalIV()
{
string text = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
this.mobjCryptoService.GenerateIV();
byte[] iv = this.mobjCryptoService.IV;
int num = iv.Length;
if (text.Length > num)
{
text = text.Substring(0, num);
}
else if (text.Length < num)
{
text = text.PadRight(num, ' ');
}
return Encoding.ASCII.GetBytes(text);
}
public string Encrypto(string Source)
{
byte[] bytes = Encoding.UTF8.GetBytes(Source);
string result;
using (MemoryStream memoryStream = new MemoryStream())
{
this.mobjCryptoService.Key = this.GetLegalKey();
this.mobjCryptoService.IV = this.GetLegalIV();
using (ICryptoTransform cryptoTransform = this.mobjCryptoService.CreateEncryptor())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
}
byte[] inArray = memoryStream.ToArray();
result = Convert.ToBase64String(inArray);
}
}
return result;
}
public string Decrypto(string Source)
{
string result;
try
{
byte[] array = Convert.FromBase64String(Source);
using (MemoryStream memoryStream = new MemoryStream(array, 0, array.Length))
{
this.mobjCryptoService.Key = this.GetLegalKey();
this.mobjCryptoService.IV = this.GetLegalIV();
using (ICryptoTransform cryptoTransform = this.mobjCryptoService.CreateDecryptor())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader(cryptoStream))
{
result = streamReader.ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
result = "";
}
return result;
}
private SymmetricAlgorithm mobjCryptoService;
private string Key;
}
}
private EncryptHelper eh = new EncryptHelper();
//加密
if (!string.IsNullOrEmpty(this.txtSource.Text))
{
this.txtResult.Text = this.eh.Encrypto(this.txtSource.Text);
}
//解密
if (!string.IsNullOrEmpty(this.txtSource.Text))
{
this.txtResult.Text = this.eh.Decrypto(this.txtSource.Text);
}
long money = 12300123;
Console.WriteLine(money.ToString("N0"));
Console.WriteLine(String.Format("{0:N0}", money));
Console.WriteLine("格式化货币");
Console.WriteLine(string.Format("{0:C}", 0.2));
Console.WriteLine(string.Format("{0:C1}", 23.15));
Console.WriteLine(string.Format("市场价:{0:C},优惠价{1:C}", 23.15, 19.82));
Console.WriteLine("格式化十进制");
Console.WriteLine(string.Format("{0:D3}", 23));
Console.WriteLine(string.Format("{0:D2}", 122));
Console.WriteLine("用分号隔开的数字,并指定小数点后的位数");
Console.WriteLine(string.Format("{0:N}", 12334));
Console.WriteLine(string.Format("{0:N3}", 12334.2345));
Console.WriteLine("格式化百分比");
Console.WriteLine("{0:P}", 0.24564);
Console.WriteLine("{0:P1}", 0.24564);
Console.WriteLine("零占位符和数字占位符");
Console.WriteLine(string.Format("{0:0000.00}", 12394.039));
Console.WriteLine(string.Format("{0:0000.00}", 194.039));
Console.WriteLine(string.Format("{0:#,#.##}", 12394.039));
Console.WriteLine(string.Format("{0:####.#}", 194.039));
Console.WriteLine(string.Format("{0,-10}", 12502));
Console.WriteLine(string.Format("{0,50}", 12502));
Console.WriteLine("日期格式化");
Console.WriteLine(string.Format("{0:d}", System.DateTime.Now));
Console.WriteLine(string.Format("{0:D}", System.DateTime.Now));
Console.WriteLine(string.Format("{0:f}", System.DateTime.Now));
Console.WriteLine(string.Format("{0:F}", System.DateTime.Now));
Console.WriteLine(string.Format("{0:g}", System.DateTime.Now));
Console.WriteLine(string.Format("{0:G}", System.DateTime.Now));
Console.WriteLine(string.Format("{0:tt}", System.DateTime.Now.ToString(new CultureInfo("en-us"))));
Console.WriteLine(string.Format("{0:T}", System.DateTime.Now));
Console.WriteLine(System.DateTime.Now.ToString("h:mm tt", new CultureInfo("en-us")));
Console.WriteLine(System.DateTime.Now.ToString("HH:mm tt"));
var date = DateTime.Parse($"3月");
var subdate = date.Subtract(new TimeSpan(1, 0, 0, 0));
Console.WriteLine($"{date}-{subdate}");
//十进制转二进制
Console.WriteLine("十进制166的二进制表示: "+Convert.ToString(166, 2));
//十进制转八进制
Console.WriteLine("十进制166的八进制表示: "+Convert.ToString(166, 8));
//十进制转十六进制 Console.WriteLine("十进制166的十六进制表示: "+Convert.ToString(166, 16));
//二进制转十进制
Console.WriteLine("二进制 111101 的十进制表示: "+Convert.ToInt32("111101", 2));
//八进制转十进制
Console.WriteLine("八进制 44 的十进制表示: "+Convert.ToInt32("44", 8));
//十六进制转十进制
Console.WriteLine("十六进制 CC的十进制表示: "+Convert.ToInt32("CC", 16));
12,300,123
12,300,123
格式化货币
¥0.20
¥23.1
市场价:¥23.15,优惠价¥19.82
格式化十进制
023
122
用分号隔开的数字,并指定小数点后的位数
12,334.00
12,334.235
格式化百分比
24.56%
24.6%
零占位符和数字占位符
12394.04
0194.04
12,394.04
194
12502
12502
日期格式化
2019/11/18
2019年11月18日
2019年11月18日 16:49
2019年11月18日 16:49:22
2019/11/18 16:49
2019/11/18 16:49:22
11/18/2019 4:49:22 PM
16:49:22
4:49 PM
16:49 下午
2022/3/1 0:00:00-2022/2/28 0:00:00
十进制166的二进制表示: 10100110
十进制166的八进制表示: 246
二进制 111101 的十进制表示: 61
八进制 44 的十进制表示: 36
十六进制 CC的十进制表示: 204
private string StringToHexString(string s, Encoding encode)
{
byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
string result = string.Empty;
for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符,以%隔开
{
result += "%" + Convert.ToString(b[i], 16);
}
return result;
}
private string HexStringToString(string hs, Encoding encode)
{
//以%分割字符串,并去掉空字符
string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++)
{
b[i] = Convert.ToByte(chars[i], 16);
}
//按照指定编码将字节数组变为字符串
return encode.GetString(b);
}
# 字符串转16进制字节数组
private static byte[] strToToHexByte(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;
}
# 字节数组转16进制字符串
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
# 从汉字转换到16进制
public static string ToHex(string s, string charset, bool fenge)
{
if ((s.Length % 2) != 0)
{
s += " ";//空格
//throw new ArgumentException("s is not valid chinese string!");
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
byte[] bytes = chs.GetBytes(s);
string str = "";
for (int i = 0; i < bytes.Length; i++)
{
str += string.Format("{0:X}", bytes[i]);
if (fenge && (i != bytes.Length - 1))
{
str += string.Format("{0}", ",");
}
}
return str.ToLower();
}
# 16进制转换成汉字
public static string UnHex(string hex, string charset)
{
if (hex == null)
throw new ArgumentNullException("hex");
hex = hex.Replace(",", "");
hex = hex.Replace("\n", "");
hex = hex.Replace("\\", "");
hex = hex.Replace(" ", "");
if (hex.Length % 2 != 0)
{
hex += "20";//空格
}
// 需要将 hex 转换成 byte 数组。
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
try
{
// 每两个字符是一个 byte。
bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
System.Globalization.NumberStyles.HexNumber);
}
catch
{
// Rethrow an exception with custom message.
throw new ArgumentException("hex is not a valid hex number!", "hex");
}
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
return chs.GetString(bytes);
}
# 随机数
public static void GenerateRandomCode(int length)
{
Hashtable hashtable = new Hashtable();
Random rm = new Random();
for (int i = 0; hashtable.Count < length; i++)
{
int nValue = rm.Next(10);
if (!hashtable.ContainsValue(nValue) && nValue != 0)
{
hashtable.Add(nValue, nValue);
Console.WriteLine(nValue.ToString());
}
}
}
public class Httphelper
{
public static string PostData(string url, string data, Action<string> action)
{
Stream stream = null;
Stream stream2 = null;
StreamReader streamReader = null;
string result = "";
try
{
Uri requestUri = new Uri(url);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Accept = "*/*";
httpWebRequest.UserAgent = "Mozilla/5.0";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 50000;
httpWebRequest.Referer = "http://www.baidu.com/";
httpWebRequest.AllowAutoRedirect = true;
httpWebRequest.ContentType = "text/xml";
bool flag = url.StartsWith("https", StringComparison.OrdinalIgnoreCase);
if (flag)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
byte[] bytes = Encoding.UTF8.GetBytes(data);
httpWebRequest.ContentLength = bytes.Length;
stream = httpWebRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream2 = httpWebRequest.GetResponse().GetResponseStream();
streamReader = new StreamReader(stream2, Encoding.GetEncoding("UTF-8"));
result = streamReader.ReadToEnd();
}
catch (WebException ex)
{
try
{
bool flag2 = ex.Response != null;
if (flag2)
{
stream2 = ex.Response.GetResponseStream();
streamReader = new StreamReader(stream2, Encoding.GetEncoding("UTF-8"));
result = streamReader.ReadToEnd();
}
}
catch (Exception ex1)
{
action(ex1.Message);
}
}
catch (Exception ex3)
{
action("发生异常:" + ex3.Message);
}
finally
{
bool flag3 = streamReader != null;
if (flag3)
{
streamReader.Close();
}
bool flag4 = stream2 != null;
if (flag4)
{
stream2.Close();
}
bool flag5 = stream != null;
if (flag5)
{
stream.Close();
}
}
return result;
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static Tuple<int, string> GetCodeByPost(string url, Action<string> action)
{
HttpWebResponse httpWebResponse = null;
int code = 0;
string body = string.Empty;
Tuple<int, string> tuple = null;
Stream stream = null;
StreamReader streamReader = null;
try
{
Uri requestUri = new Uri(url);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Accept = "*/*";
httpWebRequest.UserAgent = "Mozilla/5.0";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 10000;
httpWebRequest.Referer = "http://www.baidu.com/";
httpWebRequest.AllowAutoRedirect = true;
httpWebRequest.ContentType = "text/xml";
bool flag = url.StartsWith("https", StringComparison.OrdinalIgnoreCase);
if (flag)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
code = (int)httpWebResponse.StatusCode;
stream = httpWebResponse.GetResponseStream();
streamReader = new StreamReader(stream, Encoding.GetEncoding("UTF-8"));
body = streamReader.ReadToEnd();
tuple = new Tuple<int, string>(code, body);
}
catch (Exception ex)
{
action("发生异常:" + ex.Message);
}
finally
{
bool flag2 = streamReader != null;
if (flag2)
{
streamReader.Close();
}
bool flag3 = stream != null;
if (flag3)
{
stream.Close();
}
bool flag4 = httpWebResponse != null;
if (flag4)
{
httpWebResponse.Close();
}
}
return tuple;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data;
namespace MainShell.Extensions.Utils
{
public class ExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
}
/// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
}
/// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
}
fs = null;
disposed = true;
}
}
}
}
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TouTouRegex.cs" owner="TouTou">
// Copyright (c) TouTou Owner. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace TouTou.RegexTool
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
/// <summary>
/// 正则表达式工具,满足各种需要使用正则的需求
/// </summary>
public class TouTouRegex
{
/// <summary>
/// 检测字符串中是否包含符合正则的子集
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="reg">正则, e.g. \d+</param>
/// <returns>true:包含,反之不包含</returns>
public bool CheckContainsByReg(string source, string reg)
{
return Regex.Match(source, reg).Success;
}
/// <summary>
/// 检测整个字符串是否能匹配正则,而不是包含
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="reg">正则, e.g. ^\d+$</param>
/// <returns>true:匹配,反之不匹配</returns>
public bool CheckStringByReg(string source, string reg)
{
Regex rg = new Regex(reg, RegexOptions.IgnoreCase);
return rg.IsMatch(source);
}
/// <summary>
/// 从指定字符串中过滤出第一个符合正则匹配的子集
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="reg">正则, e.g. \d+</param>
/// <returns>源字符串的第一个匹配的子集</returns>
public string GetFirstStringByReg(string source, string reg)
{
return Regex.Match(source, reg).Groups[0].Value;
}
/// <summary>
/// 从指定字符串中过滤出所有符合正则匹配的子集
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="reg">正则, e.g. \d+</param>
/// <returns>true:匹配,反之不匹配</returns>
public List<string> GetStringByReg(string source, string reg)
{
var regex = Regex.Matches(source, reg);
List<string> list = new List<string>();
foreach (Match item in regex)
{
list.Add(item.Value);
}
return list;
}
/// <summary>
/// 从指定字符串中过滤出第一个数字
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串的第一个数字</returns>
public string GetFirstNumberByString(string source)
{
return Regex.Match(source, @"\d+").Groups[0].Value;
}
/// <summary>
/// 从指定字符串中过滤出最后一个数字
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串的最后一个数字</returns>
public string GetLastNumberByString(string source)
{
var reg = Regex.Matches(source, @"\d+");
return reg[reg.Count - 1].Value;
}
/// <summary>
/// 从指定字符串中过滤出所有数字
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串的所有数字</returns>
public List<string> GetAllNumberByString(string source)
{
var reg = Regex.Matches(source, @"\d+");
List<string> list = new List<string>();
foreach (Match item in reg)
{
list.Add(item.Value);
}
return list;
}
/// <summary>
/// 检车源字符串中是否包含数字
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>true:源字符串包含数字;false:源字符串不包含数字</returns>
public bool CheckNumberByString(string source)
{
return Regex.Match(source, @"\d").Success;
}
/// <summary>
/// 判断字符串是否全部是数字且长度等于指定长度
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="length">指定长度</param>
/// <returns>返回值</returns>
public bool CheckLengthByString(string source, int length)
{
Regex rg = new Regex(@"^\d{" + length + "}$");
return rg.IsMatch(source);
}
/// <summary>
/// 截取字符串中开始和结束字符串中间的字符串
/// </summary>
/// <param name="source">源字符串</param>
/// <param name="startStr">开始字符串</param>
/// <param name="endStr">结束字符串</param>
/// <returns>中间字符串</returns>
public string Substring(string source, string startStr, string endStr)
{
Regex rg = new Regex("(?<=(" + startStr + "))[.\\s\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(source).Value;
}
/// <summary>
/// 匹配邮箱是否合法
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>匹配结果true是邮箱反之不是邮箱</returns>
public bool CheckEmailByString(string source)
{
Regex rg = new Regex("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$", RegexOptions.IgnoreCase);
return rg.IsMatch(source);
}
/// <summary>
/// 匹配URL是否合法
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>匹配结果true是URL反之不是URL</returns>
public bool CheckURLByString(string source)
{
Regex rg = new Regex(@"^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$", RegexOptions.IgnoreCase);
return rg.IsMatch(source);
}
/// <summary>
/// 匹配日期是否合法
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>匹配结果true是日期反之不是日期</returns>
public bool CheckDateByString(string source)
{
Regex rg = new Regex(@"^(\d{4}[\/\-](0?[1-9]|1[0-2])[\/\-]((0?[1-9])|((1|2)[0-9])|30|31))|((0?[1-9]|1[0-2])[\/\-]((0?[1-9])|((1|2)[0-9])|30|31)[\/\-]\d{4})$");
return rg.IsMatch(source);
}
/// <summary>
/// 从字符串中获取第一个日期
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串中的第一个日期</returns>
public string GetFirstDateByString(string source)
{
return Regex.Match(source, @"(\d{4}[\/\-](0?[1-9]|1[0-2])[\/\-]((0?[1-9])|((1|2)[0-9])|30|31))|((0?[1-9]|1[0-2])[\/\-]((0?[1-9])|((1|2)[0-9])|30|31)[\/\-]\d{4})").Groups[0].Value;
}
/// <summary>
/// 从字符串中获取所有的日期
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串中的所有日期</returns>
public List<string> GetAllDateByString(string source)
{
var all = Regex.Matches(source, @"(\d{4}[\/\-](0?[1-9]|1[0-2])[\/\-]((0?[1-9])|((1|2)[0-9])|30|31))|((0?[1-9]|1[0-2])[\/\-]((0?[1-9])|((1|2)[0-9])|30|31)[\/\-]\d{4})");
List<string> list = new List<string>();
foreach (Match item in all)
{
list.Add(item.Value);
}
return list;
}
/// <summary>
/// 检测密码复杂度是否达标:密码中必须包含字母、数字、特称字符,至少8个字符,最多16个字符。
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>密码复杂度是否达标true是达标反之不达标</returns>
public bool CheckPasswordByString(string source)
{
Regex rg = new Regex(@"^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,16}$");
return rg.IsMatch(source);
}
/// <summary>
/// 匹配邮编是否合法
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>邮编合法返回true,反之不合法</returns>
public bool CheckPostcodeByString(string source)
{
Regex rg = new Regex(@"^\d{6}$");
return rg.IsMatch(source);
}
/// <summary>
/// 匹配电话号码是否合法
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>电话号码合法返回true,反之不合法</returns>
public bool CheckTelephoneByString(string source)
{
Regex rg = new Regex(@"^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$");
return rg.IsMatch(source);
}
/// <summary>
/// 从字符串中获取电话号码
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串中电话号码</returns>
public string GetTelephoneByString(string source)
{
return Regex.Match(source, @"(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}").Groups[0].Value;
}
/// <summary>
/// 匹配手机号码是否合法
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>手机号码合法返回true,反之不合法</returns>
public bool CheckMobilephoneByString(string source)
{
Regex rg = new Regex(@"^[1]+[3,5]+\d{9}$");
return rg.IsMatch(source);
}
/// <summary>
/// 从字符串中获取手机号码
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串中手机号码</returns>
public string GetMobilephoneByString(string source)
{
return Regex.Match(source, @"[1]+[3,5]+\d{9}").Groups[0].Value;
}
/// <summary>
/// 匹配身份证号码是否合法
/// </summary>
/// <param name="source">待匹配字符串</param>
/// <returns>身份证号码合法返回true,反之不合法</returns>
public bool CheckIDCardByString(string source)
{
Regex rg = new Regex(@"^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$");
return rg.IsMatch(source);
}
/// <summary>
/// 从字符串中获取身份证号码
/// </summary>
/// <param name="source">源字符串</param>
/// <returns>源字符串中身份证号码</returns>
public string GetIDCardByString(string source)
{
return Regex.Match(source, @"(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))").Groups[0].Value;
}
}
}
委托事件
public delegate int Foohandle(int a, int b);
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Foohandle foohandle = delegate (int a, int b) { return a + b; };
Foohandle foohandle1 = (a,b)=>a+b;
foohandle.Invoke(1,2);
foohandle1.Invoke(1,3);
}
汉字 转 二进制