From 3309f030c3b3172c2bc5708d33bd23217bd0dcf5 Mon Sep 17 00:00:00 2001 From: zpc Date: Wed, 5 Jun 2024 20:28:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 400 ++++++++++++++++ .../XLib.NetCore.Utility.sln | 25 + .../XLib.NetCore.Utility/DateTimeUtil.cs | 97 ++++ .../XLib.NetCore.Utility/FileUtil.cs | 163 +++++++ .../XLib.NetCore.Utility/LinuxShellUtil.cs | 95 ++++ .../XLib.NetCore.Utility/ReflectionCache.cs | 88 ++++ .../XLib.NetCore.Utility/SecurityUtility.cs | 448 ++++++++++++++++++ .../XLib.NetCore.Utility/TimeUtil.cs | 119 +++++ .../XLib.NetCore.Utility.csproj | 12 + 9 files changed, 1447 insertions(+) create mode 100644 .gitignore create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility.sln create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility/DateTimeUtil.cs create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility/FileUtil.cs create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility/LinuxShellUtil.cs create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility/ReflectionCache.cs create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility/SecurityUtility.cs create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility/TimeUtil.cs create mode 100644 src/XLib.NetCore.Utility/XLib.NetCore.Utility/XLib.NetCore.Utility.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9a0b35d --- /dev/null +++ b/.gitignore @@ -0,0 +1,400 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg + +# The packages folder can be ignored because of Package Restore +# **/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ + +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility.sln b/src/XLib.NetCore.Utility/XLib.NetCore.Utility.sln new file mode 100644 index 0000000..c498d58 --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.10.34916.146 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XLib.NetCore.Utility", "XLib.NetCore.Utility\XLib.NetCore.Utility.csproj", "{E97848F8-EBAB-4387-ACA9-DBF5F57635AC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E97848F8-EBAB-4387-ACA9-DBF5F57635AC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BC4E4FC3-F15C-488A-84ED-4EE5D957B1FB} + EndGlobalSection +EndGlobal diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility/DateTimeUtil.cs b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/DateTimeUtil.cs new file mode 100644 index 0000000..9436b5b --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/DateTimeUtil.cs @@ -0,0 +1,97 @@ +using System; + +namespace XLib.NetCore.Utility +{ + /// + /// + /// + public static class DateTimeUtil + { + /// + /// 根据本周周几获取当周周一 + /// + /// + /// + public static DateTime GetMondayOfThisWeek(this DateTime date) + { + // 获取今天是周几,DayOfWeek返回的是一个枚举,其中Sunday=0, Monday=1, ..., Saturday=6 + int diff = date.DayOfWeek - DayOfWeek.Monday; + + // 如果今天是周一或者之前(diff小于等于0),那么本周一就是今天或者之前的某一天 + if (diff <= 0) + { + diff += 7; // 加上一周的天数,确保diff是正数 + } + + // 返回本周一的日期(今天的日期减去diff天) + return date.AddDays(-diff); + } + + + /// + /// 根据本周周几获取当周周日 + /// + /// + /// + public static DateTime GetSundayThisWeek(this DateTime date) + { + // 获取当前日期是周几(DayOfWeek是枚举,其中Sunday的值为0) + int dayOfWeek = (int)date.DayOfWeek; + + // 计算周日距离今天的天数差 + int daysToSunday = (7 - dayOfWeek) % 7; + + // 如果今天是周日,则返回出去 + if (daysToSunday == 0) + { + return date; + } + + // 添加相应的天数得到当周的周日 + DateTime sundayThisWeek = date.AddDays(daysToSunday); + + return sundayThisWeek; + } + + + /// + /// 给时间添加周 + /// + /// + /// 周 + /// + public static DateTime AddWeeks(this DateTime dateTime, int weeksToAdd) + { + // 计算要添加的总天数,一周为7天 + int daysToAdd = weeksToAdd * 7; + + // 使用DateTime的AddDays方法添加天数 + DateTime resultDate = dateTime.AddDays(daysToAdd); + + return resultDate; + } + + + /// + /// + /// + /// + /// + public static long ConvertToUnixTimestamp(this DateTime dateTime) + { + DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime); + return dateTimeOffset.ToUnixTimeSeconds(); + } + + /// + /// + /// + /// + /// + public static long ConvertToUnixTimestampMilliseconds(this DateTime dateTime) + { + DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime); + return dateTimeOffset.ToUnixTimeMilliseconds(); + } + } +} diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility/FileUtil.cs b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/FileUtil.cs new file mode 100644 index 0000000..94a5d9c --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/FileUtil.cs @@ -0,0 +1,163 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +namespace XLib.NetCore.Utility +{ + /// + /// FileUtil + /// + public static class FileUtil + { + // 把byte保存成二进制文件 + public static void Byte2file(string file_name, byte[] b, int len) + { + using (FileStream fs = new FileStream(file_name, FileMode.OpenOrCreate)) + { + using (BinaryWriter bw = new BinaryWriter(fs)) + { + bw.Write(b, 0, len); + } + } + } + + #region 写CSV文件 + + /// + /// 根据类型,写CSV文件第一行 + /// + /// 类型 + /// 文件路径 + /// 是否追加 + public static void WriteCsvHeaderLine(string filePath, bool append) + { + using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8)) + { + // 使用反射获取字段名 + PropertyInfo[] properties = typeof(T).GetProperties(); + + string header = string.Join(",", properties.Select(p => p.Name)); + writer.WriteLine(header); + + writer.Close(); + } + } + + /// + /// 根据类型,写CSV文件第一行 + /// + /// 类型 + /// 数据 + /// 文件路径 + /// 是否追加 + public static void AppendCsvFile(T entity, string filePath, bool append) + { + using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8)) + { + // 使用反射获取字段名 + PropertyInfo[] properties = typeof(T).GetProperties(); + string data = string.Join(",", properties.Select(p => p.GetValue(entity))); + writer.WriteLine(data); + + writer.Close(); + } + } + + /// + /// 根据类型,写CSV文件第一行 + /// + /// 类型 + /// 数据 + /// 文件路径 + /// 是否追加 + public static void AppendCsvFile(IEnumerable list, string filePath, bool append) + { + using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8)) + { + // 使用反射获取字段名 + PropertyInfo[] properties = typeof(T).GetProperties(); + + // 写入数据 + foreach (var entity in list) + { + string data = string.Join(",", properties.Select(p => p.GetValue(entity))); + writer.WriteLine(data); + } + + writer.Close(); + } + } + + /// + /// 把列表数据写入CSV文件 + /// + /// 类型 + /// 列表 + /// 文件路径 + /// 是否append文件 + public static void WriteCsvHeaderFile(IEnumerable list, string filePath, bool append) + { + using (StreamWriter writer = new StreamWriter(filePath, append, Encoding.UTF8)) + { + // 使用反射获取字段名 + PropertyInfo[] properties = typeof(T).GetProperties(); + string header = string.Join(",", properties.Select(p => p.Name)); + writer.WriteLine(header); + + // 写入数据 + foreach (var entity in list) + { + string data = string.Join(",", properties.Select(p => p.GetValue(entity))); + writer.WriteLine(data); + } + writer.Close(); + } + } + + #endregion + + /// + /// 获取硬盘剩余空间,单位字节 + /// 如果失败,返回0 + /// + /// + public static long GetDiskSpace(string filePath) + { + string directoryPath = Path.GetFullPath(filePath); + + //linux平台需要创建文件夹才能获取到硬盘信息 + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + if (!Directory.Exists(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + } + + long availableSpace = 0; + + DriveInfo driveInfo = new DriveInfo(directoryPath); + if (driveInfo.IsReady) + { + availableSpace = driveInfo.AvailableFreeSpace; + return availableSpace; + } + + return availableSpace; + } + + /// + /// 检查文件后缀是否是图片 + /// + /// + /// + public static bool IsImageByExtension(string filePath) + { + string[] imageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".ico" }; // 可以根据需要添加更多扩展名 + string extension = Path.GetExtension(filePath).ToLowerInvariant(); + return imageExtensions.Contains(extension); + } + } +} diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility/LinuxShellUtil.cs b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/LinuxShellUtil.cs new file mode 100644 index 0000000..4b7498c --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/LinuxShellUtil.cs @@ -0,0 +1,95 @@ +using System; +using System.Diagnostics; +using System.IO; + +namespace XLib.NetCore.Utility +{ + /// + /// linux shell 功能 + /// + public class LinuxShellUtil + { + /// + /// 执行linux shell命令 + /// 例子:string command = "/usr/bin/systemctl restart sunny-sports.service"; + /// + /// + /// + public static int ExcuteShellCommand(string command) + { + + // 创建一个进程对象 + Process process = new Process(); + + // 设置进程启动信息 + process.StartInfo.FileName = "/bin/bash"; // 指定要执行的shell + process.StartInfo.Arguments = $"-c \"{command}\""; // 设置命令参数 + process.StartInfo.RedirectStandardOutput = true; // 重定向标准输出 + process.StartInfo.UseShellExecute = false; // 不使用操作系统shell启动进程 + process.StartInfo.CreateNoWindow = true; // 不创建窗口 + + // 启动进程 + process.Start(); + + // 读取进程的输出 + string output = process.StandardOutput.ReadToEnd(); + + // 等待进程执行完毕 + process.WaitForExit(); + + // 输出结果 + int exitCode = process.ExitCode; + process.Close(); + + Console.WriteLine($"脚本执行完毕,退出码:{exitCode}"); + + return exitCode; + } + + /// + /// 执行脚本 + /// 例子: string scriptPath = "./restart_service.sh"; + /// + /// + public static int ExcuteShellScript(string scriptPath) + { + scriptPath = Path.GetFullPath(scriptPath); + + Process process = new Process(); + process.StartInfo.FileName = "/bin/bash"; + process.StartInfo.Arguments = scriptPath; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.UseShellExecute = false; + process.StartInfo.CreateNoWindow = true; + + process.OutputDataReceived += (sender, e) => + { + if (!string.IsNullOrEmpty(e.Data)) + { + Console.WriteLine(e.Data); + } + }; + + process.ErrorDataReceived += (sender, e) => + { + if (!string.IsNullOrEmpty(e.Data)) + { + Console.WriteLine(e.Data); + } + }; + + process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + process.WaitForExit(); + + int exitCode = process.ExitCode; + process.Close(); + + Console.WriteLine($"脚本执行完毕,退出码:{exitCode}"); + + return exitCode; + } + } +} diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility/ReflectionCache.cs b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/ReflectionCache.cs new file mode 100644 index 0000000..d563b67 --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/ReflectionCache.cs @@ -0,0 +1,88 @@ +namespace XLib.NetCore.Utility +{ + using System; + using System.Collections.Concurrent; + using System.Reflection; + + /// + /// 用于缓存反射数据以提高性能。 + /// + public static class ReflectionCache + { + /// + /// 用于缓存 Type 对象,键是类型名称 + /// + private static readonly ConcurrentDictionary TypeCache = new ConcurrentDictionary(); + + /// + /// 用于缓存属性信息数组,键是 Type 对象 + /// + private static readonly ConcurrentDictionary PropertyCache = new ConcurrentDictionary(); + + /// + /// 用于缓存字段信息数组,键是 Type 对象 + /// + private static readonly ConcurrentDictionary FieldCache = new ConcurrentDictionary(); + + /// + /// 用于缓存方法信息数组,键是 Type 对象 + /// + private static readonly ConcurrentDictionary MethodCache = new ConcurrentDictionary(); + + /// + /// 用于缓存构造函数信息数组,键是 Type 对象 + /// + private static readonly ConcurrentDictionary ConstructorCache = new ConcurrentDictionary(); + + /// + /// 获取指定类型名称的 Type 对象,如果缓存中存在则使用缓存。 + /// + /// 类型的全名。 + /// 指定类型名称的 Type 对象。 + public static Type GetType(string typeName) + { + return TypeCache.GetOrAdd(typeName, t => Type.GetType(t)); + } + + /// + /// 获取指定 Type 的属性信息数组,如果缓存中存在则使用缓存。 + /// + /// Type 对象。 + /// 指定 Type 的属性信息数组。 + public static PropertyInfo[] GetProperties(Type type) + { + return PropertyCache.GetOrAdd(type, t => t.GetProperties()); + } + + /// + /// 获取指定 Type 的字段信息数组,如果缓存中存在则使用缓存。 + /// + /// Type 对象。 + /// 指定 Type 的字段信息数组。 + public static FieldInfo[] GetFields(Type type) + { + return FieldCache.GetOrAdd(type, t => t.GetFields()); + } + + /// + /// 获取指定 Type 的方法信息数组,如果缓存中存在则使用缓存。 + /// + /// Type 对象。 + /// 指定 Type 的方法信息数组。 + public static MethodInfo[] GetMethods(Type type) + { + return MethodCache.GetOrAdd(type, t => t.GetMethods()); + } + + /// + /// 获取指定 Type 的构造函数信息数组,如果缓存中存在则使用缓存。 + /// + /// Type 对象。 + /// 指定 Type 的构造函数信息数组。 + public static ConstructorInfo[] GetConstructors(Type type) + { + return ConstructorCache.GetOrAdd(type, t => t.GetConstructors()); + } + } + +} diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility/SecurityUtility.cs b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/SecurityUtility.cs new file mode 100644 index 0000000..733e55c --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/SecurityUtility.cs @@ -0,0 +1,448 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace XLib.NetCore.Utility +{ + /// + /// + /// + public static class SecurityUtility + { + /// + /// 根据文件的二进制内容取得其Hash值,用于Smartdownload的时候比较非.NetAssembly文件的版本号。 + /// + /// 文件顽症路径 + /// + public static string GetFileMD5Hash(string filename) + { + + if (!File.Exists(filename)) return ""; + + FileStream fstr = File.OpenRead(filename); + byte[] buff = new byte[fstr.Length]; + fstr.Position = 0; + fstr.Read(buff, 0, (int)fstr.Length); + fstr.Close(); + + //创建 MD5CryptoServiceProvider 实例。 + MD5 md5Hasher = MD5.Create(); + + // 把原始字符串转化成一组byte数组,并计算hash值。 + byte[] data = md5Hasher.ComputeHash(buff); + + //创建string builder + StringBuilder sBuilder = new StringBuilder(); + + //把hash值的数组16进制后,合并成字符串 + for (int i = data.Length - 1; i >= 0; i--) + { + sBuilder.Append(data[i].ToString("x2")); + } + + //return + return sBuilder.ToString(); + } + + /// + /// 计算字符串的 MD5 哈希值,并将该哈希作为 32 字符的十六进制格式字符串返回。 + /// + /// 原始字符串. + /// MD5 hash 后的32位字符串 + /// MD5 算法的哈希值大小为 128 位。 + /// 传入的引用参数为null或空字符串。 + /// + /// 2008/12/18 9:19 Created + /// + public static string GetMD5Hash(string sourceString) + { + //创建 MD5CryptoServiceProvider 实例。 + MD5 md5Hasher = MD5.Create(); + + // 把原始字符串转化成一组byte数组,并计算hash值。 + byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(sourceString)); + + //创建string builder + StringBuilder sBuilder = new StringBuilder(); + + //把hash值的数组16进制后,合并成字符串 + for (int i = data.Length - 1; i >= 0; i--) + { + sBuilder.Append(data[i].ToString("x2")); + } + + //return + return sBuilder.ToString(); + } + + + /// + /// MD5加密 + /// + /// + /// + public static string GetMD5(string sourceString) + { + using (var md5 = MD5.Create()) + { + var result = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceString)); + var strResult = BitConverter.ToString(result); + return strResult.Replace("-", ""); + } + } + /// + /// 16位的md5 + /// + /// + /// + public static string GetMD5_16(string sourceString) + { + return GetMD5(sourceString).Substring(8, 16); + } + + /// + /// 取MD5的前几位 + /// + /// + /// + /// + public static string GetMD5_Pre(string sourceString, int PreLenth) + { + return GetMD5(sourceString).Substring(0, PreLenth); + } + + /// + /// 畅由(移动积分兑换)MD5加密方式(和GetMD5得到的数据一样) + /// + /// + /// + public static string GetMD5_YD(string sourceString) + { + char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + using (var md5 = MD5.Create()) + { + var result = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceString)); + int j = result.Length; + char[] str = new char[16 * 2]; + int k = 0; + for (int i = 0; i < 16; i++) + { + byte byte0 = result[i]; + str[k++] = hexDigits[byte0 >> 4 & 0xf]; + str[k++] = hexDigits[byte0 & 0xf]; + } + return new String(str); + } + } + + + /// + /// 验证指定字符串是否和给出的 MD5 Hash值匹配。 + /// + /// 原始字符串. + /// MD5 hash 后的字符串. + /// + /// true:如果匹配; false:如果不匹配 + /// + /// + /// 传入的引用参数为null或空字符串。 + /// + /// 2008/12/18 9:21 Created + /// + public static bool VerifyMd5Hash(string sourceString, string hash) + { + //断言参数异常 + //ArgumentAssert.AssertArgumentNotNull(sourceString, "sourceString"); + //ArgumentAssert.AssertArgumentNotNull(hash, "hash"); + + // 计算字符串的 MD5 哈希值 + string hashOfInput = GetMD5Hash(sourceString); + + // 比较hash + StringComparer comparer = StringComparer.OrdinalIgnoreCase; + + if (0 == comparer.Compare(hashOfInput, hash)) + { + return true; + } + else + { + return false; + } + } + + /// + /// 计算字符串的 SHA512 哈希值,并将该哈希作为 128 字符的十六进制格式字符串返回。 + /// + /// 原始字符串. + /// SHA512 hash 之后的128位字符串。 + /// SHA512 算法的哈希值大小为 512 位。 + /// 传入的引用参数为null或空字符串。 + /// + /// 2008/12/18 10:27 Created + /// + public static string GetSHA512Hash(string sourceString) + { + //断言参数异常 + //ArgumentAssert.AssertArgumentNotNull(sourceString, "sourceString"); + + //创建 SHA512Managed 实例。 + SHA512 shaM = new SHA512Managed(); + + // 把原始字符串转化成一组byte数组,并计算hash值。 + byte[] data = shaM.ComputeHash(Encoding.Default.GetBytes(sourceString)); + + //创建string builder + StringBuilder sBuilder = new StringBuilder(); + + //把hash值的数组16进制后,合并成字符串 + for (int i = data.Length - 1; i >= 0; i--) + { + sBuilder.Append(data[i].ToString("x2")); + } + + //return + return sBuilder.ToString(); + } + + /// + /// 验证指定字符串是否和给出的 SHA512 Hash值匹配。 + /// + /// 原始字符串. + /// SHA512 hash 后的字符串. + /// + /// true:如果匹配; false:如果不匹配 + /// + /// + /// 传入的引用参数为null或空字符串。 + /// + /// 2008/12/18 10:31 Created + /// + public static bool VerifySHA512Hash(string sourceString, string hash) + { + //断言参数异常 + //ArgumentAssert.AssertArgumentNotNull(sourceString, "sourceString"); + //ArgumentAssert.AssertArgumentNotNull(hash, "hash"); + + // 计算字符串的 MD5 哈希值 + string hashOfInput = GetSHA512Hash(sourceString); + + // 比较hash + StringComparer comparer = StringComparer.OrdinalIgnoreCase; + + if (0 == comparer.Compare(hashOfInput, hash)) + { + return true; + } + else + { +#if DEBUG + Console.WriteLine("The correct hash code is: " + hashOfInput); + Console.WriteLine("The false hash code is :" + hash); +#endif + return false; + } + } + + + + + /// + /// 生成一个唯一的字符串(16个字符) + /// + /// 唯一字符串 + /// + /// + /// + /// 2010/7/28 14:31 Created + /// + public static string GenerateUniqueStringID() + { + long i = 1; + foreach (byte b in Guid.NewGuid().ToByteArray()) + { + i *= ((int)b + 1); + } + return string.Format("{0:x}", i - DateTime.Now.Ticks); + } + + /// + /// 转换成base64 + /// + /// The value. + /// + /// Write At 2012-8-2 + public static string ToBase64String(string value) + { + value = Convert.ToBase64String(Encoding.GetEncoding("gb2312").GetBytes(value)); + //它将“+”和“/”改成了“!”和“-”, + value = value.Replace('+', '!'); + value = value.Replace('/', '-'); + + return value; + + } + /// + /// Froms the base64 string. + /// + /// The value. + /// + /// Write At 2012-8-2 + public static string FromBase64String(string value) + { + // //它将“+”和“/”改成了“!”和“-”, + value = value.Replace('!', '+'); + value = value.Replace('-', '/'); + + value = Encoding.GetEncoding("gb2312").GetString(Convert.FromBase64String(value)); + return value; + } + + /// + /// HMACSHA1加密,并使用Base64编码 + /// + /// + /// + /// + public static string GetHMACSHA1(string value, string key) + { + HMACSHA1 hmacsha1 = new HMACSHA1(); + hmacsha1.Key = Encoding.UTF8.GetBytes(key); + byte[] dataBuffer = Encoding.UTF8.GetBytes(value); + byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer); + return Convert.ToBase64String(hashBytes); + } + public static String MD5Encode(String origin, String charsetname) + { + var md5 = MD5.Create(); + var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(origin)); + var sb = new StringBuilder(); + foreach (byte b in bs) + { + sb.Append(b.ToString("x2")); + } + //所有字符转为小写 + return sb.ToString().ToLower(); + } + + /// + /// MD5字符串加密 + /// + /// + /// 加密后字符串 + public static string GenerateMD5(string txt) + { + using (MD5 mi = MD5.Create()) + { + byte[] buffer = Encoding.Default.GetBytes(txt); + //开始加密 + byte[] newBuffer = mi.ComputeHash(buffer); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < newBuffer.Length; i++) + { + sb.Append(newBuffer[i].ToString("x2")); + } + return sb.ToString(); + } + } + + #region 对称加密 + //DES、3DES、AES + #endregion + + #region 非对称加密 + //如果要用C#的私钥进行加密,需要使用第三方的加解密组件BouncyCastle来实现 + public static void CreateRSAKey() + { + //设置[公钥私钥]文件路径 + string privateKeyPath = @"d:\\PrivateKey.xml"; + string publicKeyPath = @"d:\\PublicKey.xml"; + //创建RSA对象 + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); + //生成RSA[公钥私钥] + //string privateKey = rsa.ToXmlString(true); + //string publicKey = rsa.ToXmlString(false); + + string privateKey = Convert.ToBase64String(rsa.ExportCspBlob(true)); + string publicKey = Convert.ToBase64String(rsa.ExportCspBlob(false)); + + + //将密钥写入指定路径 + File.WriteAllText(privateKeyPath, privateKey);//文件内包含公钥和私钥 + File.WriteAllText(publicKeyPath, publicKey);//文件内只包含公钥 + } + + /// + /// rsa公钥加密 + /// + /// 加密的明文 + /// 公钥 + /// + public static string RSA_EncryptData(string res, string publicKey) + { + //C#默认只能使用[公钥]进行加密(想使用[公钥解密]可使用第三方组件BouncyCastle来实现) + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); + //将公钥导入到RSA对象中 + rsa.FromXmlString(publicKey); + //加密 + byte[] data = Encoding.UTF8.GetBytes(res); + var bytes = rsa.Encrypt(data, false); + return Convert.ToBase64String(bytes); + } + /// + /// rsa私钥解密 + /// + /// 解密的密文 + /// 私钥 + /// + public static string RSA_DecryptData(string res, string privateKey) + { + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); + //将私钥导入RSA对象中 + rsa.FromXmlString(privateKey); + //解密 + byte[] data = Convert.FromBase64String(res); + var bytes = rsa.Decrypt(data, false); + return Encoding.UTF8.GetString(bytes); + } + + /// + /// rsa私钥签名 + /// + /// 签名的数据 + /// 私钥 + /// 返回签名 + public static string RSA_Sign(string res, string privateKey) + { + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); + //将私钥导入RSA对象中 + rsa.FromXmlString(privateKey); + //将数据使用MD5进行消息摘要,然后对摘要进行签名并返回签名数据 + byte[] data = Encoding.UTF8.GetBytes(res); + var bytes = rsa.SignData(data, "MD5"); + return Convert.ToBase64String(bytes); + } + /// + /// rsa公钥验证签名 + /// + /// 签名的数据 + /// 签名 + /// 公钥 + /// + public static bool RSA_VerifySign(string res, string sign, string publicKey) + { + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); + //将公钥导入到RSA对象中 + rsa.FromXmlString(publicKey); + //验证签名 + byte[] data = Encoding.UTF8.GetBytes(res); + byte[] data_sign = Encoding.UTF8.GetBytes(sign); + return rsa.VerifyData(data, "MD5", data_sign); + } + #endregion + + } +} + + diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility/TimeUtil.cs b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/TimeUtil.cs new file mode 100644 index 0000000..b5c2743 --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/TimeUtil.cs @@ -0,0 +1,119 @@ +using System; + +namespace XLib.NetCore.Utility +{ + /// + /// 时间帮助类 + /// + public static class TimeUtil + { + /// + /// 获得时间戳 + /// + /// + public static long get_time_stamp() + { + TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1); + return (long)ts.TotalMilliseconds; + } + + /// + /// 获得时间戳 + /// + /// + public static long get_time_stamp(this DateTime time) + { + TimeSpan ts = time.ToUniversalTime() - new DateTime(1970, 1, 1); + return (long)ts.TotalMilliseconds; + } + + /// + /// 获得时间戳 秒 + /// + /// + /// + public static int TimeToStamp() + { + TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1); + return (int)ts.TotalSeconds; + } + + /// + /// 时间戳转本地时间-时间戳精确到秒 + /// + public static DateTime ToLocalTimeDateBySeconds(long unix) + { + var dto = DateTimeOffset.FromUnixTimeSeconds(unix); + return dto.ToLocalTime().DateTime; + } + + /// + /// 时间转时间戳Unix-时间戳精确到秒 + /// + public static long ToUnixTimestampBySeconds(DateTime dt) + { + DateTimeOffset dto = new DateTimeOffset(dt); + return dto.ToUnixTimeSeconds(); + } + + + /// + /// 时间戳转本地时间-时间戳精确到毫秒 + /// + public static DateTime ToLocalTimeDateByMilliseconds(long unix) + { + var dto = DateTimeOffset.FromUnixTimeMilliseconds(unix); + return dto.ToLocalTime().DateTime; + } + + /// + /// 时间转时间戳Unix-时间戳精确到毫秒 + /// + public static long ToUnixTimestampByMilliseconds(DateTime dt) + { + DateTimeOffset dto = new DateTimeOffset(dt); + return dto.ToUnixTimeMilliseconds(); + } + + /// + /// 秒转时间文字 + /// + /// + /// + public static string ConvertSecondsToTimeSpanCondensed(long totalSeconds) + { + if (totalSeconds <= 0) + { + return "0秒"; + } + + long days = totalSeconds / (60 * 60 * 24); + totalSeconds %= (60 * 60 * 24); + + long hours = totalSeconds / (60 * 60); + totalSeconds %= (60 * 60); + + long minutes = totalSeconds / 60; + long seconds = totalSeconds % 60; + + string timeString = ""; + + if (days > 0) + { + timeString = $"{days}天"; + } + if (hours > 0 || timeString.Length > 0) // 如果有天数或者已经添加了小时,则显示小时 + { + timeString += $"{hours}小时"; + } + if (minutes > 0 || timeString.Length > 0) // 如果有天数或者已经添加了小时,则显示小时 + { + timeString += $"{minutes}分钟"; + } + + timeString += $"{seconds}秒"; + + return timeString; // 移除开头可能的多余空格 + } + } +} diff --git a/src/XLib.NetCore.Utility/XLib.NetCore.Utility/XLib.NetCore.Utility.csproj b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/XLib.NetCore.Utility.csproj new file mode 100644 index 0000000..fc8bbd9 --- /dev/null +++ b/src/XLib.NetCore.Utility/XLib.NetCore.Utility/XLib.NetCore.Utility.csproj @@ -0,0 +1,12 @@ + + + + netstandard2.1 + enable + True + 帮助类 + 通用的帮助类 + git@123.207.203.228:server/XLib.NetCore.Utility.git + + +