using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
using System.IO;
|
using System.Drawing;
|
using System.Drawing.Imaging;
|
using System.IO.Packaging;
|
using System.Web;
|
using System.IO.Compression;
|
using System.Security.Cryptography;
|
|
namespace Helpers
|
{
|
public static partial class Tool
|
{
|
/// <summary>
|
/// 文件输出至指定路径
|
/// </summary>
|
/// <param name="path">文件物理路径,例:C:\test.txt</param>
|
/// <param name="content">要输出的内容,以utf-8的格式</param>
|
/// <returns>输出结果</returns>
|
public static bool PrintTXTFile(string path, string content)
|
{
|
try
|
{
|
StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8);
|
sw.WriteLine(content);
|
sw.Close();
|
sw.Dispose();
|
return true;
|
}
|
catch (Exception ex)
|
{
|
Tool.PrintLog("添加内容失败", ex.Message);
|
return false;
|
}
|
}
|
|
/// <summary>
|
/// 取得列表类别
|
/// </summary>
|
/// <param name="number">type</param>
|
/// <returns></returns>
|
public static string GetType(int number)
|
{
|
string str = "";
|
switch (number)
|
{
|
case -1: str = "最新添加"; break;
|
case 0: str = "学习路上"; break;
|
case 1: str = "个人私文"; break;
|
case 2: str = "加密"; break;
|
case 3: str = "随笔记"; break;
|
default: str = ""; break;
|
}
|
return str;
|
}
|
|
/// <summary>
|
/// 无效字符清空
|
/// </summary>
|
/// <param name="str">待过滤的字符串</param>
|
/// <param name="list">要过滤的字符列表</param>
|
/// <returns>过滤掉无效内容后的字符串</returns>
|
public static string FilterStr(string str, List<string> list)
|
{
|
if (string.IsNullOrWhiteSpace(str)) { return ""; }
|
foreach (var a in list)
|
{
|
str = Helpers.Tool.ReplaceString(str, a, "");
|
}
|
return str;
|
}
|
|
/// <summary>
|
/// 处理html常见标签的字符串
|
/// </summary>
|
/// <param name="str">待处理的字符串</param>
|
/// <returns>处理后的字符串</returns>
|
public static string HtmlCodeStr(string str)
|
{
|
str = Helpers.Tool.ReplaceString(str, "<html>", "");
|
str = Helpers.Tool.ReplaceString(str, "</html>", "\f");
|
str = Helpers.Tool.ReplaceString(str, "<body>", "");
|
str = Helpers.Tool.ReplaceString(str, "</body>", "\n");
|
str = Helpers.Tool.ReplaceString(str, "<head>", "");
|
str = Helpers.Tool.ReplaceString(str, "</head>", "\n");
|
str = Helpers.Tool.ReplaceString(str, "<div>", "");
|
str = Helpers.Tool.ReplaceString(str, "</div>", "\n");
|
str = Helpers.Tool.ReplaceString(str, "<p>", "\r");
|
str = Helpers.Tool.ReplaceString(str, "</p>", "\r");
|
str = Helpers.Tool.ReplaceString(str, "<hr>", "\r");
|
str = Helpers.Tool.ReplaceString(str, "<a>", "");
|
str = Helpers.Tool.ReplaceString(str, "</a>", "");
|
str = Helpers.Tool.ReplaceString(str, "<content>", "\n");
|
str = Helpers.Tool.ReplaceString(str, "</content>", "\n");
|
str = Helpers.Tool.ReplaceString(str, "<iframe>", "\n");
|
str = Helpers.Tool.ReplaceString(str, "</iframe>", "\n");
|
str = Helpers.Tool.ReplaceString(str, "<h1>", "");
|
str = Helpers.Tool.ReplaceString(str, "</h1>", "");
|
str = Helpers.Tool.ReplaceString(str, "<h2>", "");
|
str = Helpers.Tool.ReplaceString(str, "</h2>", "");
|
str = Helpers.Tool.ReplaceString(str, "<h3>", "");
|
str = Helpers.Tool.ReplaceString(str, "</h3>", "");
|
str = Helpers.Tool.ReplaceString(str, "<h4>", "");
|
str = Helpers.Tool.ReplaceString(str, "</h4>", "");
|
str = Helpers.Tool.ReplaceString(str, "<i>", "");
|
str = Helpers.Tool.ReplaceString(str, "</i>", "");
|
str = Helpers.Tool.ReplaceString(str, ">", "<");
|
str = Helpers.Tool.ReplaceString(str, "<", ">");
|
str = Helpers.Tool.ReplaceString(str, " ", " ");
|
str = Helpers.Tool.ReplaceString(str, "<br>", "\n\r");
|
str = Helpers.Tool.ReplaceString(str, "<br />", "\n\r");
|
str = Helpers.Tool.ReplaceString(str, "<Br>", "\n\r");
|
str = Helpers.Tool.ReplaceString(str, "<Br />", "\n\r");
|
str = Helpers.Tool.ReplaceString(str, "\"", "");
|
return str;
|
}
|
|
/// <summary>
|
/// IPV4地址验证
|
/// </summary>
|
/// <returns></returns>
|
public static bool IpAddressSign(string ip)
|
{
|
try
|
{
|
if (ip == "::1") { return true; }
|
ip = ip.Trim();
|
string[] ips = ip.Split('.');
|
if (ips.Length != 4) { return false; }
|
foreach (var a in ips)
|
{
|
int splitAddr = int.Parse(a);
|
if (splitAddr < 0 && splitAddr > 256) { return false; }
|
}
|
return true;
|
}
|
catch
|
{
|
return false;
|
}
|
}
|
|
/// <summary>
|
/// 32位大写MD5加密
|
/// </summary>
|
/// <param name="str">待加密的字符串</param>
|
/// <returns></returns>
|
public static string MD5(string str)
|
{
|
string result = MD5(str, true, 32);
|
return result;
|
}
|
|
/// <summary>
|
/// 32位MD5加密
|
/// </summary>
|
/// <param name="str">待加密的字符串</param>
|
/// <param name="IsUpper">是否大写</param>
|
/// <returns></returns>
|
public static string MD5(string str, bool IsUpper)
|
{
|
string result = MD5(str, IsUpper, 32);
|
return result;
|
}
|
|
/// <summary>
|
/// MD5加密
|
/// </summary>
|
/// <param name="str">待加密的字符串</param>
|
/// <param name="IsUpper">是否大写</param>
|
/// <param name="bit">加密位数16或者32</param>
|
/// <returns></returns>
|
public static string MD5(string str, bool IsUpper, int bit)
|
{
|
System.Security.Cryptography.MD5 md = new System.Security.Cryptography.MD5CryptoServiceProvider();
|
byte[] byteStream = System.Text.Encoding.UTF8.GetBytes(str);
|
byte[] temp = md.ComputeHash(byteStream);
|
StringBuilder tempStr = new StringBuilder();
|
string result = null;
|
foreach (var a in temp)
|
{
|
tempStr.Append(a.ToString("x2"));
|
}
|
if (IsUpper)
|
{
|
result = tempStr.ToString().ToUpper();
|
}
|
else
|
{
|
result = tempStr.ToString().ToLower();
|
}
|
if (bit == 16)
|
{
|
result = result.Substring(8, 16);
|
}
|
else if (bit == 32)
|
{
|
result = result.ToString();
|
}
|
else
|
{
|
result = string.Empty;
|
}
|
return result;
|
}
|
|
/// <summary>
|
/// Sha256加密
|
/// </summary>
|
/// <param name="str"></param>
|
/// <returns></returns>
|
public static string Sha256(string str) {
|
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
|
SHA256 sha256 = new SHA256CryptoServiceProvider();
|
|
byte[] retVal = sha256.ComputeHash(bytValue);
|
StringBuilder sb = new StringBuilder();
|
for (int i = 0; i < retVal.Length; i++)
|
{
|
sb.Append(retVal[i].ToString("x2"));
|
}
|
return sb.ToString().ToUpper();
|
}
|
|
/// <summary>
|
/// 验证身份证号格式
|
/// </summary>
|
/// <param name="code">身份证号</param>
|
/// <returns>正确或错误</returns>
|
public static bool ValidateIdentityCode(string code)
|
{
|
if (code.Length != 15 && code.Length != 18) { return false; }
|
if (code[0] == 48)
|
{ return false; }
|
foreach (char c in code)
|
{
|
if (c > 47 && c < 58)
|
{ continue; }
|
else if (c == 88 || c == 120)
|
{
|
if (code[17] == c)
|
{ continue; }
|
else
|
{ return false; }
|
}
|
else
|
{ return false; }
|
}
|
return true;
|
}
|
|
/// <summary>
|
/// 验证手机号格式
|
/// </summary>
|
/// <param name="mobile">手机号</param>
|
/// <returns>正确或错误</returns>
|
public static bool ValidateMobile(string mobile)
|
{
|
if (mobile.Length != 11) { return false; }
|
if (mobile[0] != 49) { return false; }
|
foreach (char c in mobile)
|
{
|
if (c < 48 || c > 57)
|
{
|
return false;
|
}
|
}
|
return true;
|
}
|
|
/// <summary>
|
/// 验证邮箱格式
|
/// </summary>
|
/// <param name="mail">邮箱账号</param>
|
/// <returns>正确或错误</returns>
|
public static bool ValidateMail(string mail)
|
{
|
|
if (mail.Length < 5) { return false; }
|
|
//反转邮箱账号字符串
|
string descMail = null;
|
foreach (char c in mail.Reverse())
|
{
|
descMail += c;
|
}
|
|
int atindex = descMail.IndexOf('@');
|
int dotindex = descMail.IndexOf('.');
|
if (atindex < 3)
|
{
|
return false;
|
}
|
if (dotindex < 1)
|
{
|
return false;
|
}
|
|
if (mail[0] == '@' || mail[0] == '.') { return false; }
|
if (dotindex > atindex) { return false; }
|
return true;
|
}
|
|
/// <summary>
|
/// 过滤非法Sql字符
|
/// </summary>
|
/// <param name="str"></param>
|
/// <returns></returns>
|
public static string SQLFilter(string str)
|
{
|
if (string.IsNullOrEmpty(str))
|
{
|
return "";
|
}
|
List<string> strs = new List<string>();
|
strs.Add("'--");
|
strs.Add(";");
|
strs.Add("|");
|
return FilterStr(str, strs);
|
}
|
|
/// <summary>
|
/// 图片转base64
|
/// </summary>
|
/// <param name="bmp"></param>
|
/// <returns></returns>
|
public static string ImgToBase64String(Bitmap bmp)
|
{
|
try
|
{
|
MemoryStream ms = new MemoryStream();
|
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
|
byte[] arr = new byte[ms.Length];
|
ms.Position = 0;
|
ms.Read(arr, 0, (int)ms.Length);
|
ms.Close();
|
return Convert.ToBase64String(arr);
|
}
|
catch
|
{
|
return null;
|
}
|
}
|
|
/// <summary>
|
/// 图片转base64
|
/// </summary>
|
/// <param name="fs">文件流</param>
|
/// <returns></returns>
|
public static string ImgToBase64String(FileStream fs) {
|
byte[] bytes = new byte[fs.Length];
|
fs.Read(bytes, 0, (int)fs.Length);
|
string base64Str = Convert.ToBase64String(bytes);
|
return base64Str;
|
}
|
|
/// <summary>
|
/// base64保存成图片,返回Bitmap对象
|
/// </summary>
|
/// <param name="strbase64"></param>
|
public static Bitmap Base64StringToImage(string filePath, string fileName, string strbase64, ImageType type)
|
{
|
|
try
|
{
|
byte[] arr = Convert.FromBase64String(strbase64);
|
MemoryStream ms = new MemoryStream(arr);
|
Bitmap bmp = new Bitmap(ms);
|
|
switch (type)
|
{
|
case ImageType.Jpg: bmp.Save($@"{filePath}\{fileName}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); break;
|
case ImageType.Bmp: bmp.Save($@"{filePath}\{fileName}.bmp", ImageFormat.Bmp); break;
|
case ImageType.Gif: bmp.Save($@"{filePath}\{fileName}.gif", ImageFormat.Gif); break;
|
case ImageType.Png: bmp.Save($@"{filePath}\{fileName}.png", ImageFormat.Png); break;
|
default: bmp.Save($@"{filePath}\{fileName}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); break;
|
}
|
//bmp.Save($@"{savePath}\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
|
//bmp.Save(@"d:\"test.bmp", ImageFormat.Bmp);
|
//bmp.Save(@"d:\"test.gif", ImageFormat.Gif);
|
//bmp.Save(@"d:\"test.png", ImageFormat.Png);
|
ms.Close();
|
return bmp;
|
}
|
catch (Exception ex)
|
{
|
Helpers.Tool.PrintLog_Error(ex.Message, ex.StackTrace);
|
return null;
|
}
|
}
|
|
/// <summary>
|
/// 创建文件夹
|
/// </summary>
|
/// <param name="filePath">路径</param>
|
/// <param name="folderName">文件夹名</param>
|
/// <returns></returns>
|
public static string CreateDirectory(string filePath, string folderName)
|
{
|
|
if (string.IsNullOrEmpty(filePath))
|
{
|
if (string.IsNullOrEmpty(folderName))
|
{
|
return "";
|
}
|
}
|
else
|
{
|
if (filePath.Substring(filePath.Length - 1) == @"\")
|
{
|
filePath = filePath.Substring(0, filePath.Length - 1);
|
}
|
}
|
string path = filePath + @"\" + folderName;
|
try
|
{
|
if (!System.IO.Directory.Exists(path))
|
{
|
Directory.CreateDirectory(path);
|
}
|
}
|
catch (Exception ex)
|
{
|
Helpers.Tool.PrintLog_Info("出错了!", ex.Message + ex.StackTrace);
|
return null;
|
}
|
Helpers.Tool.PrintLog_Info(path, "");
|
return path;
|
}
|
|
/// <summary>
|
/// 将时间转换成秒级的时间戳
|
/// </summary>
|
/// <param name="time">要转换的时间</param>
|
/// <returns></returns>
|
public static int DateTimeToDateStr(DateTime time)
|
{
|
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
|
int timeStr = (int)(DateTime.Now - startTime).TotalSeconds;
|
return timeStr;
|
}
|
/// <summary>
|
/// 将时间戳转换成C#的时间
|
/// </summary>
|
/// <param name="dateStr"></param>
|
/// <returns></returns>
|
public static DateTime DateStrToDateTime(int dateStr)
|
{
|
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
|
long lTime = long.Parse(dateStr.ToString() + "0000000");
|
TimeSpan toNow = new TimeSpan(lTime);
|
return Tool.FormatDate(startTime.Add(toNow));
|
}
|
|
/// <summary>
|
/// 按字典的key升序拼接字典,字典key和value的类型为string
|
/// </summary>
|
/// <param name="dic"></param>
|
/// <returns></returns>
|
public static string SplicingDic(Dictionary<string, string> dic)
|
{
|
if (dic == null)
|
{
|
return null;
|
}
|
var temp = dic.OrderBy(o => o.Key, StringComparer.OrdinalIgnoreCase);
|
StringBuilder result = new StringBuilder();
|
foreach (var a in temp)
|
{
|
result.Append($"{a.Key}={a.Value}&");
|
}
|
string str = result.ToString();
|
str = str.Substring(0, str.Length - 1);
|
return str;
|
}
|
|
/// <summary>
|
/// ASE加密
|
/// </summary>
|
/// <param name="text">待加密的文本</param>
|
/// <param name="key">密钥(可选)</param>
|
/// <param name="iv">位移量(可选)</param>
|
/// <returns>加密后的密文</returns>
|
public static string ASEEncode(string text, string key = "abcd", string iv = "dddd") {
|
Helpers.ASEEncryption ase = new Helpers.ASEEncryption();
|
return ase.Encrypt(text, key, iv);
|
}
|
|
/// <summary>
|
/// ASE解密
|
/// </summary>
|
/// <param name="text">密文</param>
|
/// <param name="key">密钥(可选)</param>
|
/// <param name="iv">位移量(可选)</param>
|
/// <returns>解密后的文本</returns>
|
public static string ASEDecode(string pwdText, string key = "abcd", string iv = "dddd")
|
{
|
Helpers.ASEEncryption ase = new Helpers.ASEEncryption();
|
return ase.Decrypt(pwdText, key, iv);
|
}
|
|
/// <summary>
|
/// 将指定的文件夹压缩成ZIP文件
|
/// </summary>
|
/// <param name="folderName">待压缩的文件夹路径</param>
|
/// <param name="compressedFileName">压缩后的文件存放路径(含文件名,例C:\test.zip)</param>
|
/// <param name="overrideExisting">是否覆盖同名文件</param>
|
/// <returns></returns>
|
[Obsolete("已弃用,此方法会在压缩包中自动创建了个文件", true)]
|
public static bool PackageFolderZIP(string folderName, string compressedFileName, bool overrideExisting)
|
{
|
if (folderName.EndsWith(@"\"))
|
folderName = folderName.Remove(folderName.Length - 1);
|
bool result = false;
|
if (!Directory.Exists(folderName))
|
{
|
return result;
|
}
|
|
if (!overrideExisting && File.Exists(compressedFileName))
|
{
|
return result;
|
}
|
try
|
{
|
using (Package package = Package.Open(compressedFileName, FileMode.Create))
|
{
|
var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
|
foreach (string fileName in fileList)
|
{
|
|
//The path in the package is all of the subfolders after folderName
|
string pathInPackage;
|
pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);
|
|
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
|
PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
|
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
|
{
|
fileStream.CopyTo(packagePartDocument.GetStream());
|
}
|
}
|
}
|
result = true;
|
}
|
catch (Exception e)
|
{
|
throw new Exception("Error zipping folder " + folderName, e);
|
}
|
|
return result;
|
}
|
|
/// <summary>
|
/// 解压ZIP文件
|
/// </summary>
|
/// <param name="folderName">待解压的文件路径</param>
|
/// <param name="compressedFileName">解压后存放的目录</param>
|
/// <param name="overrideExisting">是否进行覆盖</param>
|
/// <returns></returns>
|
public static bool UncompressFileZIP(string folderName, string compressedFileName, bool overrideExisting)
|
{
|
bool result = false;
|
try
|
{
|
if (!File.Exists(compressedFileName))
|
{
|
return result;
|
}
|
|
DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
|
if (!directoryInfo.Exists)
|
directoryInfo.Create();
|
|
using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
|
{
|
foreach (PackagePart packagePart in package.GetParts())
|
{
|
ExtractPart(packagePart, folderName, overrideExisting);
|
}
|
}
|
|
result = true;
|
}
|
catch (Exception e)
|
{
|
throw new Exception("Error unzipping file " + compressedFileName, e);
|
}
|
|
return result;
|
}
|
|
/// <summary>
|
/// 将指定的文件夹压缩成ZIP文件
|
/// </summary>
|
/// <param name="folderName">待压缩的文件夹路径</param>
|
/// <param name="compressedFileName">压缩后的文件存放路径(含文件名,例C:\test.zip)</param>
|
/// <param name="overrideExisting">是否覆盖同名文件</param>
|
/// <returns></returns>
|
public static bool ZIPCompressFolder(string folderName, string compressedFileName, bool overrideExisting) {
|
if (folderName.EndsWith(@"\"))
|
folderName = folderName.Remove(folderName.Length - 1);
|
bool result = false;
|
if (!Directory.Exists(folderName))
|
{
|
return result;
|
}
|
|
if (!overrideExisting && File.Exists(compressedFileName))
|
{
|
return result;
|
}
|
if (File.Exists(compressedFileName)) {
|
File.Delete(compressedFileName);
|
}
|
try
|
{
|
ZipFile.CreateFromDirectory(folderName, compressedFileName);
|
return true;
|
}
|
catch (Exception ex) {
|
return false;
|
}
|
}
|
|
/// <summary>
|
/// 将多个文件压缩成ZIP文件
|
/// </summary>
|
/// <param name="fileList">待压缩的文件路径列表</param>
|
/// <param name="compressedFileName">压缩后的文件存放路径(含文件名,例C:\test.zip)</param>
|
/// <param name="overrideExisting">是否覆盖同名文件</param>
|
/// <param name="replaceFolderName">打包后移除的路径部分,示例格式: C:\Files\</param>
|
/// <returns></returns>
|
public static bool ZIPCompressFiles(List<string> fileList, string compressedFileName, bool overrideExisting,string replaceFolderName = "") {
|
bool result = false;
|
|
try
|
{
|
using (Package package = Package.Open(compressedFileName, FileMode.Create))
|
{
|
Dictionary<string, int> dic = new Dictionary<string, int>();
|
foreach (string fileName in fileList)
|
{
|
|
if (!File.Exists(fileName)) {
|
return result;
|
}
|
|
//The path in the package is all of the subfolders after folderName
|
string pathInPackage;
|
pathInPackage = Path.GetDirectoryName(fileName).Replace(replaceFolderName, string.Empty) + "/" + Path.GetFileName(fileName);
|
if (dic.ContainsKey(pathInPackage)) {
|
dic[pathInPackage] = dic[pathInPackage]++;
|
int maxLen = Path.GetFileName(fileName).Length;
|
if (Path.GetFileName(fileName).LastIndexOf(".") > -1) {
|
maxLen = Path.GetFileName(fileName).LastIndexOf(".");
|
}
|
pathInPackage = Path.GetFileName(fileName).Substring(0, maxLen) + $"({dic[pathInPackage]})" + Path.GetFileName(fileName).Substring(maxLen);
|
}
|
else {
|
dic.Add(pathInPackage, 0);
|
}
|
Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
|
PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
|
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
|
{
|
fileStream.CopyTo(packagePartDocument.GetStream());
|
}
|
}
|
}
|
result = true;
|
}
|
catch (Exception e)
|
{
|
throw new Exception("Error Directory : " + fileList.ToJson(), e);
|
}
|
return result;
|
}
|
|
/// <summary>
|
/// 解压ZIP文件
|
/// </summary>
|
/// <param name="compressedFileName">待解压的文件</param>
|
/// <param name="TofolderName">解压后存放的目录</param>
|
/// <returns></returns>
|
public static bool UnZIPCompressFolder(string compressedFileName, string TofolderName)
|
{
|
bool result = false;
|
if (!File.Exists(compressedFileName)) {
|
throw new Exception("未找到相关文件");
|
}
|
if (TofolderName.EndsWith(@"\")) {
|
TofolderName = TofolderName.Remove(TofolderName.Length - 1);
|
}
|
CreateDirectory(TofolderName, "");
|
try
|
{
|
ZipFile.ExtractToDirectory(compressedFileName, TofolderName);
|
return true;
|
}
|
catch (Exception ex) {
|
return false;
|
}
|
|
}
|
|
/// <summary>
|
/// 密码加密
|
/// </summary>
|
/// <param name="account">账号</param>
|
/// <param name="pwd">密码</param>
|
public static string EncryptPwd(string account, string pwd) {
|
return Helpers.Tool.MD5(account + Helpers.Tool.MD5("Moli") + pwd);
|
}
|
|
/// <summary>
|
/// 获取一个新的token
|
/// </summary>
|
public static string CreateToken(string key) {
|
string time = DateTime.Now.ToString("yyyyMMddHHmmssfff");
|
string guid = Guid.NewGuid().ToString();
|
string param1 = "Moli";
|
string param2 = MD5(MD5(time) + Sha256(time) + param1 + Sha256(guid));
|
|
string p1 = Sha256(param2);
|
|
string token = p1.Insert(Convert.ToInt32(time.Substring(12)) % p1.Length,
|
MD5(time).Insert(Convert.ToInt32(time.Substring(12)) % MD5(time).Length, MD5(guid)))
|
.Insert(Convert.ToInt32(time.Substring(12)) % p1.Length, Sha256(guid));
|
return key + token.Substring(20, token.Length - 30);
|
}
|
|
/// <summary>
|
/// 将文件流的bytes长度转成相应的标准单位
|
/// </summary>
|
/// <param name="BytesSize">待转的长度,单位bytes</param>
|
/// <returns>转换后的标准单位(B,KB,MB,GB,TB)</returns>
|
public static string FileSizeChange(long BytesSize) {
|
long maxSize = 1024;
|
if (BytesSize < 1024) {
|
return BytesSize.ToString() + "B";
|
} else if (BytesSize < maxSize * maxSize) {
|
return Math.Round(Math.Ceiling(BytesSize * 1000 / 1024.00) / 1000.00, 3).ToString() + "KB";
|
} else if (BytesSize < maxSize * maxSize * maxSize) {
|
return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00)) / 1000.00, 3).ToString() + "MB";
|
} else if (BytesSize < maxSize * maxSize * maxSize * maxSize) {
|
return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00)) / 1000.00, 3).ToString() + "GB";
|
}
|
return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00) / 1024.00) / 1000.00, 3).ToString() + "TB";
|
}
|
/// <summary>
|
/// 将文件流的bytes长度转成指定的标准单位
|
/// </summary>
|
/// <param name="BytesSize">待转的长度,单位bytes</param>
|
/// <param name="fileSizeUnit">转换后的单位</param>
|
/// <returns>转换后的长度(含单位)</returns>
|
public static string FileSizeChange(long BytesSize, FileSizeUnit fileSizeUnit) {
|
switch (fileSizeUnit) {
|
case FileSizeUnit.Bytes: return BytesSize.ToString() + "B";
|
case FileSizeUnit.KB: return Math.Round(Math.Ceiling(BytesSize * 1000 / 1024.00) / 1000.00, 3).ToString() + "KB";
|
case FileSizeUnit.MB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00)) / 1000.00, 3).ToString() + "MB";
|
case FileSizeUnit.GB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00)) / 1000.00, 3).ToString() + "GB";
|
case FileSizeUnit.TB: return Math.Round(Math.Ceiling(BytesSize * 1000 / (1024.00 * 1024.00 * 1024.00) / 1024.00) / 1000.00, 3).ToString() + "TB";
|
default: return FileSizeChange(BytesSize);
|
}
|
}
|
|
/// <summary>
|
/// 将带单位的大小换算成以Byte为单位的大小
|
/// </summary>
|
/// <param name="sizeStr">文件大小,含单位,示例数据:2.31MB</param>
|
/// <returns>换算Byte成后的长度</returns>
|
public static long FileSizeChangeForByte(string sizeStr) {
|
string unit = "";
|
long size = 0;
|
int index = sizeStr.ToUpper().IndexOf("B");
|
if (index == -1) {
|
throw new Exception("无效的单位字符");
|
}
|
if (sizeStr[index - 1] > 71)
|
{
|
unit = sizeStr.Substring(index - 1);
|
size = Convert.ToInt64(sizeStr.Substring(0, index - 1));
|
}
|
return FileSizeChangeForByte(size, (FileSizeUnit)Enum.Parse(typeof(FileSizeUnit), unit));
|
}
|
/// <summary>
|
/// 将带单位的大小换算成以Byte为单位的大小
|
/// </summary>
|
/// <param name="size">文件大小,不含单位,示例数据:2.31</param>
|
/// <param name="fileSizeUnit">文件大小单位</param>
|
/// <returns>换算Byte成后的长度</returns>
|
public static long FileSizeChangeForByte(double size, FileSizeUnit fileSizeUnit) {
|
switch (fileSizeUnit)
|
{
|
case FileSizeUnit.Bytes: return Convert.ToInt64(size);
|
case FileSizeUnit.KB: return Convert.ToInt64(size*1024);
|
case FileSizeUnit.MB: return Convert.ToInt64(size * 1024 * 1024);
|
case FileSizeUnit.GB: return Convert.ToInt64(size * 1024 * 1024 * 1024);
|
case FileSizeUnit.TB: return Convert.ToInt64(size * 1024 * 1024 * 1024 * 1024);
|
default: return Convert.ToInt64(size);
|
}
|
}
|
|
/// <summary>
|
/// 将Stream写入FileStream中并返回FileStream
|
/// </summary>
|
/// <param name="s">Stream对象</param>
|
/// <param name="fs">FileStream对象</param>
|
/// <returns>写入后的FileStream</returns>
|
public static FileStream WriteFileStream(Stream s, FileStream fs) {
|
using (BinaryWriter bw = new BinaryWriter(fs)) {
|
bw.Write(s.ToByte());
|
return fs;
|
}
|
}
|
|
/// <summary>
|
/// 路径统一格式化
|
/// </summary>
|
/// <param name="root">待格式化的路径</param>
|
/// <param name="endChar">是否包含路径结束符'\',默认包含</param>
|
/// <returns>格式化后的路径</returns>
|
public static string GetRoot(string root,bool endChar = true) {
|
if (string.IsNullOrWhiteSpace(root)) {
|
return "";
|
}
|
|
if (endChar) {
|
if (root.EndsWith("\\"))
|
{
|
return root;
|
}
|
else {
|
root += "\\";
|
return root;
|
}
|
} else {
|
if (root.EndsWith("\\"))
|
{
|
root = root.Remove(root.Length - 1);
|
return root;
|
}
|
else
|
{
|
return root;
|
}
|
}
|
}
|
/// <summary>
|
/// 路径统一格式化
|
/// </summary>
|
/// <param name="root">待格式化的路径</param>
|
/// <param name="fileName">文件名</param>
|
/// <returns>格式化后的路径</returns>
|
public static string GetRoot(string root, string fileName)
|
{
|
if (string.IsNullOrWhiteSpace(root))
|
{
|
return "";
|
}
|
if (!root.EndsWith("\\"))
|
{
|
root += "\\";
|
}
|
root += fileName;
|
return root;
|
}
|
|
|
/// <summary>
|
/// 通过完整的文件路径取得Etag
|
/// </summary>
|
/// <param name="FileName">File Full Name</param>
|
/// <returns></returns>
|
public static string GetEtag(string FileName) {
|
if (!File.Exists(FileName)) {
|
throw new Exception("找不到该文件");
|
}
|
FileInfo fi = new FileInfo(FileName);
|
Int64 FileSize = Convert.ToInt64(fi.OpenRead().Length);
|
if (FileSize > Int64.MaxValue) {
|
throw new Exception("文件过大!");
|
}
|
|
return GetEtag(fi, FileSize);
|
}
|
|
/// <summary>
|
/// 获取文件的Etag
|
/// </summary>
|
/// <param name="fi">System.IO.FileInfo</param>
|
/// <param name="FileSize">文件Stream.leng</param>
|
/// <returns></returns>
|
public static string GetEtag(System.IO.FileInfo fi,Int64 FileSize) {
|
string Etag = "";
|
Etag = MD5("Etag:" + fi.FullName + "----" + fi.LastWriteTimeUtc + "----" + FileSize, true);
|
return Etag;
|
}
|
|
/// <summary>
|
/// 检测文件路径中是否含有非法字符
|
/// </summary>
|
/// <param name="path"></param>
|
/// <returns></returns>
|
public static bool ExistsFilePath(string path) {
|
string[] s = "\\ : ( ? \" < > |".Split(" ");
|
foreach (string a in s) {
|
if (path.IndexOf(a) > -1) {
|
return false;
|
}
|
}
|
return true;
|
}
|
|
private static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)
|
{
|
string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/');
|
|
if (!Directory.Exists(Path.GetDirectoryName(stringPart)))
|
Directory.CreateDirectory(Path.GetDirectoryName(stringPart));
|
|
if (!overrideExisting && File.Exists(stringPart))
|
return;
|
using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))
|
{
|
packagePart.GetStream().CopyTo(fileStream);
|
}
|
}
|
}
|
|
/// <summary>
|
/// 枚举图片格式
|
/// </summary>
|
public enum ImageType {
|
Jpg = 0,
|
Bmp = 1,
|
Gif = 2,
|
Png = 3
|
}
|
|
public enum FileSizeUnit {
|
bit = 0,
|
Bytes = 1,
|
KB = 2,
|
MB = 3,
|
GB = 4,
|
TB = 5,
|
}
|
}
|