初始化上传
63
.gitattributes
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
###############################################################################
|
||||
# Set default behavior to automatically normalize line endings.
|
||||
###############################################################################
|
||||
* text=auto
|
||||
|
||||
###############################################################################
|
||||
# Set default behavior for command prompt diff.
|
||||
#
|
||||
# This is need for earlier builds of msysgit that does not have it on by
|
||||
# default for csharp files.
|
||||
# Note: This is only used by command line
|
||||
###############################################################################
|
||||
#*.cs diff=csharp
|
||||
|
||||
###############################################################################
|
||||
# Set the merge driver for project and solution files
|
||||
#
|
||||
# Merging from the command prompt will add diff markers to the files if there
|
||||
# are conflicts (Merging from VS is not affected by the settings below, in VS
|
||||
# the diff markers are never inserted). Diff markers may cause the following
|
||||
# file extensions to fail to load in VS. An alternative would be to treat
|
||||
# these files as binary and thus will always conflict and require user
|
||||
# intervention with every merge. To do so, just uncomment the entries below
|
||||
###############################################################################
|
||||
#*.sln merge=binary
|
||||
#*.csproj merge=binary
|
||||
#*.vbproj merge=binary
|
||||
#*.vcxproj merge=binary
|
||||
#*.vcproj merge=binary
|
||||
#*.dbproj merge=binary
|
||||
#*.fsproj merge=binary
|
||||
#*.lsproj merge=binary
|
||||
#*.wixproj merge=binary
|
||||
#*.modelproj merge=binary
|
||||
#*.sqlproj merge=binary
|
||||
#*.wwaproj merge=binary
|
||||
|
||||
###############################################################################
|
||||
# behavior for image files
|
||||
#
|
||||
# image files are treated as binary by default.
|
||||
###############################################################################
|
||||
#*.jpg binary
|
||||
#*.png binary
|
||||
#*.gif binary
|
||||
|
||||
###############################################################################
|
||||
# diff behavior for common document formats
|
||||
#
|
||||
# Convert binary document formats to text before diffing them. This feature
|
||||
# is only available from the command line. Turn it on by uncommenting the
|
||||
# entries below.
|
||||
###############################################################################
|
||||
#*.doc diff=astextplain
|
||||
#*.DOC diff=astextplain
|
||||
#*.docx diff=astextplain
|
||||
#*.DOCX diff=astextplain
|
||||
#*.dot diff=astextplain
|
||||
#*.DOT diff=astextplain
|
||||
#*.pdf diff=astextplain
|
||||
#*.PDF diff=astextplain
|
||||
#*.rtf diff=astextplain
|
||||
#*.RTF diff=astextplain
|
||||
341
.gitignore
vendored
Normal file
@@ -0,0 +1,341 @@
|
||||
## 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/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
.idea/
|
||||
# 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
|
||||
|
||||
# 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/
|
||||
|
||||
# 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
|
||||
*.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
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
.JustCode
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# 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
|
||||
# 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
|
||||
|
||||
# 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
|
||||
*- Backup*.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 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/
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
# 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/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
37
README.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# VS_Tools
|
||||
|
||||
#### 介绍
|
||||
小工具
|
||||
|
||||
#### 软件架构
|
||||
软件架构说明
|
||||
|
||||
|
||||
#### 安装教程
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 使用说明
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 参与贡献
|
||||
|
||||
1. Fork 本仓库
|
||||
2. 新建 Feat_xxx 分支
|
||||
3. 提交代码
|
||||
4. 新建 Pull Request
|
||||
|
||||
|
||||
#### 码云特技
|
||||
|
||||
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
|
||||
2. 码云官方博客 [blog.gitee.com](https://blog.gitee.com)
|
||||
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解码云上的优秀开源项目
|
||||
4. [GVP](https://gitee.com/gvp) 全称是码云最有价值开源项目,是码云综合评定出的优秀开源项目
|
||||
5. 码云官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
||||
6. 码云封面人物是一档用来展示码云会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
||||
27
常用工具集.sln
Normal file
@@ -0,0 +1,27 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.10.35122.118
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "常用工具集", "常用工具集\常用工具集.csproj", "{8D1F09A1-EF83-FF37-E4DA-6C486B550A71}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{8D1F09A1-EF83-FF37-E4DA-6C486B550A71}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{8D1F09A1-EF83-FF37-E4DA-6C486B550A71}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8D1F09A1-EF83-FF37-E4DA-6C486B550A71}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8D1F09A1-EF83-FF37-E4DA-6C486B550A71}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {EE908508-1911-4343-87B2-D66338C656E1}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
48
常用工具集/App.axaml
Normal file
@@ -0,0 +1,48 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="常用工具集.App"
|
||||
xmlns:local="using:常用工具集"
|
||||
xmlns:semi="https://irihi.tech/semi"
|
||||
xmlns:u="https://irihi.tech/ursa"
|
||||
xmlns:usemi="https://irihi.tech/ursa/themes/semi"
|
||||
xmlns:helpers="clr-namespace:Irihi.Avalonia.Shared.Helpers;assembly=Irihi.Avalonia.Shared"
|
||||
xmlns:viewModels="clr-namespace:常用工具集.ViewModels"
|
||||
x:CompileBindings="True"
|
||||
x:DataType="viewModels:ApplicationViewModel">
|
||||
<!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
|
||||
|
||||
<!--<Application.DataTemplates>
|
||||
<local:ViewLocator/>
|
||||
</Application.DataTemplates>-->
|
||||
|
||||
<Application.Styles>
|
||||
<semi:SemiTheme Locale="zh-CN"/>
|
||||
<semi:SemiPopupAnimations/>
|
||||
<usemi:SemiTheme Locale="zh-CN" />
|
||||
|
||||
<semi:ColorPickerSemiTheme />
|
||||
<semi:DataGridSemiTheme />
|
||||
<semi:TreeDataGridSemiTheme />
|
||||
|
||||
<!--This style is created to demonstrate Dialog StyleClass feature. This style is applied to Dialog Window-->
|
||||
<Style Selector="u|DefaultDialogWindow.Custom">
|
||||
<Style Selector="^ /template/ Button#PART_OKButton">
|
||||
<Setter Property="Content" Value="CUSTOM"/>
|
||||
<Setter Property="helpers:ClassHelper.Classes" Value="Warning"></Setter>
|
||||
</Style>
|
||||
</Style>
|
||||
</Application.Styles>
|
||||
|
||||
|
||||
<TrayIcon.Icons>
|
||||
<TrayIcons>
|
||||
<TrayIcon Icon="/Assets/favicon.ico" MacOSProperties.IsTemplateIcon="true" ToolTipText="Semi Avalonia Demo">
|
||||
<TrayIcon.Menu>
|
||||
<NativeMenu>
|
||||
<NativeMenuItem Header="Exit" Command="{Binding ExitCommand}" />
|
||||
</NativeMenu>
|
||||
</TrayIcon.Menu>
|
||||
</TrayIcon>
|
||||
</TrayIcons>
|
||||
</TrayIcon.Icons>
|
||||
</Application>
|
||||
50
常用工具集/App.axaml.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System.Linq;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Data.Core;
|
||||
using Avalonia.Data.Core.Plugins;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using 常用工具集.ViewModels;
|
||||
using 常用工具集.Views;
|
||||
|
||||
namespace 常用工具集
|
||||
{
|
||||
public partial class App : Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
this.DataContext = new ApplicationViewModel();
|
||||
}
|
||||
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
// Avoid duplicate validations from both Avalonia and the CommunityToolkit.
|
||||
// More info: https://docs.avaloniaui.net/docs/guides/development-guides/data-validation#manage-validationplugins
|
||||
DisableAvaloniaDataAnnotationValidation();
|
||||
desktop.MainWindow = new MainWindow();
|
||||
//desktop.MainWindow = new MainWindow
|
||||
//{
|
||||
// DataContext = new MainWindowViewModel(),
|
||||
//};
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
private void DisableAvaloniaDataAnnotationValidation()
|
||||
{
|
||||
// Get an array of plugins to remove
|
||||
var dataValidationPluginsToRemove = BindingPlugins.DataValidators.OfType<DataAnnotationsValidationPlugin>().ToArray();
|
||||
|
||||
// remove each entry found
|
||||
foreach (var plugin in dataValidationPluginsToRemove)
|
||||
{
|
||||
BindingPlugins.DataValidators.Remove(plugin);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
常用工具集/Assets/AcrobatXI/amtlib.dll
Normal file
BIN
常用工具集/Assets/Cat/empty.dll
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
常用工具集/Assets/Cat/empty.png
Normal file
|
After Width: | Height: | Size: 21 KiB |
BIN
常用工具集/Assets/Cat/full.dll
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
常用工具集/Assets/Cat/full.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
常用工具集/Assets/ColorBag/卡机色.gif
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
常用工具集/Assets/ColorBag/古代紫.gif
Normal file
|
After Width: | Height: | Size: 106 KiB |
BIN
常用工具集/Assets/ColorBag/地平线.gif
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
常用工具集/Assets/ColorBag/墨绿.gif
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
常用工具集/Assets/ColorBag/太阳橙.gif
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
常用工具集/Assets/ColorBag/孔雀绿.gif
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
常用工具集/Assets/ColorBag/月亮黄.gif
Normal file
|
After Width: | Height: | Size: 97 KiB |
BIN
常用工具集/Assets/ColorBag/桃色.gif
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
常用工具集/Assets/ColorBag/梨色.gif
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
常用工具集/Assets/ColorBag/椰棕色.gif
Normal file
|
After Width: | Height: | Size: 107 KiB |
BIN
常用工具集/Assets/ColorBag/橘红色.gif
Normal file
|
After Width: | Height: | Size: 99 KiB |
BIN
常用工具集/Assets/ColorBag/正红.gif
Normal file
|
After Width: | Height: | Size: 98 KiB |
BIN
常用工具集/Assets/ColorBag/洋红.gif
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
常用工具集/Assets/ColorBag/浅灰.gif
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
常用工具集/Assets/ColorBag/浅绿.gif
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
常用工具集/Assets/ColorBag/浓蓝.gif
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
常用工具集/Assets/ColorBag/浓蓝绿.gif
Normal file
|
After Width: | Height: | Size: 105 KiB |
BIN
常用工具集/Assets/ColorBag/深蓝.gif
Normal file
|
After Width: | Height: | Size: 100 KiB |
BIN
常用工具集/Assets/ColorBag/深青灰.gif
Normal file
|
After Width: | Height: | Size: 109 KiB |
BIN
常用工具集/Assets/ColorBag/濡雨色.gif
Normal file
|
After Width: | Height: | Size: 116 KiB |
BIN
常用工具集/Assets/ColorBag/灰瓷.gif
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
常用工具集/Assets/ColorBag/牡丹红.gif
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
常用工具集/Assets/ColorBag/琉璃色.gif
Normal file
|
After Width: | Height: | Size: 108 KiB |
BIN
常用工具集/Assets/ColorBag/秋菊黄.gif
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
常用工具集/Assets/ColorBag/紫水晶.gif
Normal file
|
After Width: | Height: | Size: 100 KiB |
BIN
常用工具集/Assets/ColorBag/紫色.gif
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
常用工具集/Assets/ColorBag/绯红.gif
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
常用工具集/Assets/ColorBag/芥予色.gif
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
常用工具集/Assets/ColorBag/草绿.gif
Normal file
|
After Width: | Height: | Size: 105 KiB |
BIN
常用工具集/Assets/ColorBag/蔷薇色.gif
Normal file
|
After Width: | Height: | Size: 98 KiB |
BIN
常用工具集/Assets/ColorBag/薰衣草.gif
Normal file
|
After Width: | Height: | Size: 95 KiB |
BIN
常用工具集/Assets/ColorBag/贝色.gif
Normal file
|
After Width: | Height: | Size: 111 KiB |
BIN
常用工具集/Assets/ColorBag/那不勒斯黄.gif
Normal file
|
After Width: | Height: | Size: 106 KiB |
BIN
常用工具集/Assets/ColorBag/酒红.gif
Normal file
|
After Width: | Height: | Size: 105 KiB |
BIN
常用工具集/Assets/ColorBag/钴蓝.gif
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
常用工具集/Assets/ColorBag/铬绿.gif
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
常用工具集/Assets/ColorBag/铬黄.gif
Normal file
|
After Width: | Height: | Size: 98 KiB |
BIN
常用工具集/Assets/ColorBag/闪光绿.gif
Normal file
|
After Width: | Height: | Size: 100 KiB |
BIN
常用工具集/Assets/ColorBag/青灰绿.gif
Normal file
|
After Width: | Height: | Size: 104 KiB |
BIN
常用工具集/Assets/ColorBag/青紫色.gif
Normal file
|
After Width: | Height: | Size: 108 KiB |
BIN
常用工具集/Assets/ColorBag/青金石.gif
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
常用工具集/Assets/ColorBag/鲜黄色.gif
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
常用工具集/Assets/ColorBag/鸠羽灰.gif
Normal file
|
After Width: | Height: | Size: 110 KiB |
BIN
常用工具集/Assets/ColorBag/麦色.gif
Normal file
|
After Width: | Height: | Size: 106 KiB |
BIN
常用工具集/Assets/ColorBag/黄橙色.gif
Normal file
|
After Width: | Height: | Size: 105 KiB |
BIN
常用工具集/Assets/ColorBag/黑灰.gif
Normal file
|
After Width: | Height: | Size: 105 KiB |
BIN
常用工具集/Assets/FTP/File.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
常用工具集/Assets/FTP/Folder.png
Normal file
|
After Width: | Height: | Size: 3.0 KiB |
BIN
常用工具集/Assets/Navi/background.png
Normal file
|
After Width: | Height: | Size: 17 KiB |
BIN
常用工具集/Assets/Navi/down.png
Normal file
|
After Width: | Height: | Size: 4.1 KiB |
BIN
常用工具集/Assets/Navi/left.png
Normal file
|
After Width: | Height: | Size: 4.0 KiB |
BIN
常用工具集/Assets/WPS/show.jpg
Normal file
|
After Width: | Height: | Size: 59 KiB |
BIN
常用工具集/Assets/favicon.ico
Normal file
|
After Width: | Height: | Size: 17 KiB |
50
常用工具集/Base/DelegateCommand.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace 常用工具集.Base
|
||||
{
|
||||
public class DelegateCommand : ICommand
|
||||
{
|
||||
public Action<object> ExecuteCommand = null;
|
||||
public Func<object, bool> CanExecuteCommand = null;
|
||||
|
||||
public event EventHandler CanExecuteChanged;
|
||||
|
||||
public DelegateCommand()
|
||||
{
|
||||
}
|
||||
|
||||
public DelegateCommand(Action<object> Command)
|
||||
{
|
||||
ExecuteCommand = Command;
|
||||
}
|
||||
|
||||
public bool CanExecute(object paramter)
|
||||
{
|
||||
if (CanExecuteCommand != null)
|
||||
{
|
||||
return CanExecuteCommand(paramter);
|
||||
}
|
||||
else
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Execute(object paramter)
|
||||
{
|
||||
if (ExecuteCommand != null)
|
||||
ExecuteCommand(paramter);
|
||||
}
|
||||
|
||||
public void RaiseCanExecuteChanged()
|
||||
{
|
||||
if (CanExecuteChanged != null)
|
||||
CanExecuteChanged(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
51
常用工具集/Base/GlobalValues.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Notifications;
|
||||
using Avalonia.Input.Platform;
|
||||
using Avalonia.Platform.Storage;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace 常用工具集.Base
|
||||
{
|
||||
internal class GlobalValues
|
||||
{
|
||||
public static Ursa.Controls.WindowNotificationManager? NotificationManager { get; set; }
|
||||
public static Window MainWindow { get; internal set; }
|
||||
public static IStorageProvider StorageProvider { get; internal set; }
|
||||
public static IClipboard Clipboard { get; internal set; }
|
||||
|
||||
public static void ShowNotification(string title, string message, NotificationType type)
|
||||
{
|
||||
if (NotificationManager != null)
|
||||
{
|
||||
NotificationManager?.Show(new Notification(title, message), showIcon: true, showClose: false, type: type);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Error(string message)
|
||||
{
|
||||
if (NotificationManager != null)
|
||||
{
|
||||
NotificationManager?.Show(message, NotificationType.Error, TimeSpan.FromSeconds(1), true, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Warning(string message)
|
||||
{
|
||||
if (NotificationManager != null)
|
||||
{
|
||||
NotificationManager?.Show(message, NotificationType.Warning, TimeSpan.FromSeconds(1), true, false);
|
||||
}
|
||||
}
|
||||
public static void Success(string message)
|
||||
{
|
||||
if (NotificationManager != null)
|
||||
{
|
||||
NotificationManager?.Show(message, NotificationType.Success, TimeSpan.FromSeconds(1), true, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
19
常用工具集/Base/ViewModelBase.cs
Normal file
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace 常用工具集.Base
|
||||
{
|
||||
public class ViewModelBase : INotifyPropertyChanged
|
||||
{
|
||||
public event PropertyChangedEventHandler PropertyChanged;
|
||||
public void NotifyPropertyChanged([CallerMemberName] string propertyname = null)
|
||||
{
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
|
||||
}
|
||||
}
|
||||
}
|
||||
3
常用工具集/FodyWeavers.xml
Normal file
@@ -0,0 +1,3 @@
|
||||
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
|
||||
<PropertyChanged />
|
||||
</Weavers>
|
||||
74
常用工具集/FodyWeavers.xsd
Normal file
@@ -0,0 +1,74 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
|
||||
<!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->
|
||||
<xs:element name="Weavers">
|
||||
<xs:complexType>
|
||||
<xs:all>
|
||||
<xs:element name="PropertyChanged" minOccurs="0" maxOccurs="1">
|
||||
<xs:complexType>
|
||||
<xs:attribute name="InjectOnPropertyNameChanged" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if the On_PropertyName_Changed feature is enabled.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="TriggerDependentProperties" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if the Dependent properties feature is enabled.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="EnableIsChangedProperty" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if the IsChanged property feature is enabled.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="EventInvokerNames" type="xs:string">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to change the name of the method that fires the notify event. This is a string that accepts multiple values in a comma separated form.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="CheckForEquality" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should be inserted. If false, equality checking will be disabled for the project.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="CheckForEqualityUsingBaseEquals" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should use the Equals method resolved from the base class.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="UseStaticEqualsFromBase" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to control if equality checks should use the static Equals method resolved from the base class.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="SuppressWarnings" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to turn off build warnings from this weaver.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="SuppressOnPropertyNameChangedWarning" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Used to turn off build warnings about mismatched On_PropertyName_Changed methods.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:all>
|
||||
<xs:attribute name="VerifyAssembly" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="VerifyIgnoreCodes" type="xs:string">
|
||||
<xs:annotation>
|
||||
<xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="GenerateXsd" type="xs:boolean">
|
||||
<xs:annotation>
|
||||
<xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
23
常用工具集/Program.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Dialogs;
|
||||
|
||||
namespace 常用工具集
|
||||
{
|
||||
internal sealed class Program
|
||||
{
|
||||
// Initialization code. Don't use any Avalonia, third-party APIs or any
|
||||
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
|
||||
// yet and stuff might break.
|
||||
[STAThread]
|
||||
public static void Main(string[] args) => BuildAvaloniaApp()
|
||||
.StartWithClassicDesktopLifetime(args);
|
||||
|
||||
// Avalonia configuration, don't remove; also used by visual designer.
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
.WithInterFont()
|
||||
.LogToTrace();
|
||||
}
|
||||
}
|
||||
31
常用工具集/Utility/BindingProxy.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace 常用工具集.Utility
|
||||
{
|
||||
//public class BindingProxy : Freezable
|
||||
//{
|
||||
// #region Overrides of Freezable
|
||||
|
||||
// protected override Freezable CreateInstanceCore()
|
||||
// {
|
||||
// return new BindingProxy();
|
||||
// }
|
||||
|
||||
// #endregion Overrides of Freezable
|
||||
|
||||
// public object Data
|
||||
// {
|
||||
// get { return (object)GetValue(DataProperty); }
|
||||
// set { SetValue(DataProperty, value); }
|
||||
// }
|
||||
|
||||
// // Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
|
||||
// public static readonly DependencyProperty DataProperty =
|
||||
// DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
|
||||
//}
|
||||
}
|
||||
39
常用工具集/Utility/CZGL.SystemInfo/CPU/CPUHelper.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static class CPUHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前系统消耗的 CPU 时间
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static CPUTime GetCPUTime()
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
return WindowsCPU.GetCPUTime();
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
return LinuxCPU.GetCPUTime();
|
||||
return new CPUTime();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算 CPU 使用率
|
||||
/// </summary>
|
||||
/// <param name="oldTime"></param>
|
||||
/// <param name="newTime"></param>
|
||||
/// <returns></returns>
|
||||
public static double CalculateCPULoad(CPUTime oldTime, CPUTime newTime)
|
||||
{
|
||||
ulong totalTicksSinceLastTime = newTime.SystemTime - oldTime.SystemTime;
|
||||
ulong idleTicksSinceLastTime = newTime.IdleTime - oldTime.IdleTime;
|
||||
|
||||
double ret = 1.0f - ((totalTicksSinceLastTime > 0) ? ((double)idleTicksSinceLastTime) / totalTicksSinceLastTime : 0);
|
||||
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
29
常用工具集/Utility/CZGL.SystemInfo/CPU/CPUTime.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public struct CPUTime
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="idleTime"></param>
|
||||
/// <param name="systemTime"></param>
|
||||
public CPUTime(ulong idleTime, ulong systemTime)
|
||||
{
|
||||
IdleTime = idleTime;
|
||||
SystemTime = systemTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CPU 空闲时间
|
||||
/// </summary>
|
||||
public ulong IdleTime { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// CPU 工作时间
|
||||
/// </summary>
|
||||
public ulong SystemTime { get; private set; }
|
||||
}
|
||||
}
|
||||
21
常用工具集/Utility/CZGL.SystemInfo/CPU/FILETIME.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct FILETIME
|
||||
{
|
||||
/// <summary>
|
||||
/// 时间的低位部分
|
||||
/// </summary>
|
||||
public uint DateTimeLow;
|
||||
|
||||
/// <summary>
|
||||
/// 时间的高位部分
|
||||
/// </summary>
|
||||
public uint DateTimeHigh;
|
||||
}
|
||||
}
|
||||
55
常用工具集/Utility/CZGL.SystemInfo/CPU/LinuxCPU.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Linux
|
||||
/// </summary>
|
||||
public static class LinuxCPU
|
||||
{
|
||||
const string Path = "/proc/stat";
|
||||
|
||||
/// <summary>
|
||||
/// 获取 CPU 时间
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static CPUTime GetCPUTime()
|
||||
{
|
||||
ulong IdleTime = 0;
|
||||
ulong SystemTime = 0;
|
||||
try
|
||||
{
|
||||
var text = File.ReadAllLines(Path);
|
||||
|
||||
foreach (var item in text)
|
||||
{
|
||||
if (!item.StartsWith("cpu")) continue;
|
||||
#if NET6_0_OR_GREATER
|
||||
var values = item.Split(" ", StringSplitOptions.RemoveEmptyEntries).ToArray();
|
||||
SystemTime += (ulong)(values[1..].Select(x => decimal.Parse(x)).Sum());
|
||||
#else
|
||||
var values = item.Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries).ToArray();
|
||||
SystemTime += (ulong)(values.ToList().GetRange(1, values.Length).Select(x => decimal.Parse(x)).Sum());
|
||||
#endif
|
||||
|
||||
IdleTime += ulong.Parse(values[4]);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex.ToString());
|
||||
Debug.Assert(false, ex.Message);
|
||||
throw new PlatformNotSupportedException($"{RuntimeInformation.OSArchitecture.ToString()} {Environment.OSVersion.Platform.ToString()} {Environment.OSVersion.ToString()}");
|
||||
}
|
||||
|
||||
return new CPUTime(IdleTime, SystemTime);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
71
常用工具集/Utility/CZGL.SystemInfo/CPU/WindowsCPU.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Windows
|
||||
/// </summary>
|
||||
public partial class WindowsCPU
|
||||
{
|
||||
/*
|
||||
IdleTime 空闲时间
|
||||
KernelTime 内核时间
|
||||
UserTime 用户时间
|
||||
|
||||
系统时间 = 内核时间 + 用户时间
|
||||
SystemTime = KernelTime + UserTime
|
||||
|
||||
*/
|
||||
|
||||
/// <summary>
|
||||
/// 在多处理器系统上,返回的值是所有处理器指定时间的总和
|
||||
/// </summary>
|
||||
/// <remarks><see href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getsystemtimes"/></remarks>
|
||||
/// <param name="lpIdleTime">指向 FILETIME 结构的指针,该结构接收系统空闲的时间量</param>
|
||||
/// <param name="lpKernelTime">指向 FILETIME 结构的指针,该结构接收系统在内核模式下执行的时间量(包括所有进程中的所有线程以及所有处理器上的所有线程)。此时间值还包括系统空闲的时间</param>
|
||||
/// <param name="lpUserTime">指向 FILETIME 结构的指针,该结构接收系统在 User 模式下执行的时间量(包括所有进程中的所有线程以及所有处理器上的所有线程)</param>
|
||||
/// <returns></returns>
|
||||
#if NET7_0_OR_GREATER
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetSystemTimes(out FILETIME lpIdleTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
|
||||
#else
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool GetSystemTimes(out FILETIME lpIdleTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
|
||||
#endif
|
||||
/// <summary>
|
||||
/// 获取 CPU 工作时间
|
||||
/// </summary>
|
||||
/// <param name="lpIdleTime"></param>
|
||||
/// <param name="lpKernelTime"></param>
|
||||
/// <param name="lpUserTime"></param>
|
||||
/// <returns></returns>
|
||||
public static CPUTime GetCPUTime(FILETIME lpIdleTime, FILETIME lpKernelTime, FILETIME lpUserTime)
|
||||
{
|
||||
var IdleTime = ((ulong)lpIdleTime.DateTimeHigh << 32) | lpIdleTime.DateTimeLow;
|
||||
var KernelTime = ((ulong)lpKernelTime.DateTimeHigh << 32) | lpKernelTime.DateTimeLow;
|
||||
var UserTime = ((ulong)lpUserTime.DateTimeHigh << 32) | lpUserTime.DateTimeLow;
|
||||
|
||||
var SystemTime = KernelTime + UserTime;
|
||||
|
||||
return new CPUTime(IdleTime, SystemTime);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 CPU 工作时间
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static CPUTime GetCPUTime()
|
||||
{
|
||||
FILETIME lpIdleTime = default;
|
||||
FILETIME lpKernelTime = default;
|
||||
FILETIME lpUserTime = default;
|
||||
if (!GetSystemTimes(out lpIdleTime, out lpKernelTime, out lpUserTime))
|
||||
{
|
||||
return default;
|
||||
}
|
||||
return GetCPUTime(lpIdleTime, lpKernelTime, lpUserTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
129
常用工具集/Utility/CZGL.SystemInfo/Disk/DiskInfo.cs
Normal file
@@ -0,0 +1,129 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 磁盘信息
|
||||
/// </summary>
|
||||
public class DiskInfo
|
||||
{
|
||||
private readonly DriveInfo _info;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取磁盘类
|
||||
/// </summary>
|
||||
public DriveInfo DriveInfo => _info;
|
||||
|
||||
private DiskInfo(DriveInfo info)
|
||||
{
|
||||
_info = info;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 驱动器名称
|
||||
/// <para>ex: C:\</para>
|
||||
/// </summary>
|
||||
public string Id => _info.Name;
|
||||
|
||||
/// <summary>
|
||||
/// 磁盘名称
|
||||
/// <para>ex:<br />
|
||||
/// Windows: system<br />
|
||||
/// Linux: /dev
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public string Name => _info.Name;
|
||||
|
||||
/// <summary>
|
||||
/// 获取驱动器类型
|
||||
/// </summary>
|
||||
/// <remarks>获取驱动器类型,如 CD-ROM、可移动、网络或固定</remarks>
|
||||
public DriveType DriveType => _info.DriveType;
|
||||
|
||||
/// <summary>
|
||||
/// 文件系统
|
||||
/// <para>
|
||||
/// Windows: NTFS、 CDFS...<br />
|
||||
/// Linux: rootfs、tmpfs、binfmt_misc...
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public string FileSystem => _info.DriveFormat;
|
||||
|
||||
/// <summary>
|
||||
/// 磁盘剩余容量(以字节为单位)
|
||||
/// </summary>
|
||||
public long FreeSpace => _info.AvailableFreeSpace;
|
||||
|
||||
/// <summary>
|
||||
/// 磁盘总容量(以字节为单位)
|
||||
/// </summary>
|
||||
public long TotalSize => _info.TotalSize;
|
||||
|
||||
/// <summary>
|
||||
/// 磁盘剩余可用容量
|
||||
/// </summary>
|
||||
public long UsedSize => TotalSize - FreeSpace;
|
||||
|
||||
/// <summary>
|
||||
/// 磁盘根目录位置
|
||||
/// </summary>
|
||||
public string RootPath => _info.RootDirectory.FullName;
|
||||
|
||||
/// <summary>
|
||||
/// 获取本地所有磁盘信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static DiskInfo[] GetDisks()
|
||||
{
|
||||
return DriveInfo.GetDrives().Where(x => x.IsReady).Select(x => new DiskInfo(x)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 Docker 运行的容器其容器文件系统在主机中的存储位置
|
||||
/// </summary>
|
||||
/// <remarks>程序需要在宿主机运行才有效果,在容器中运行,调用此API获取不到相关信息</remarks>
|
||||
/// <returns></returns>
|
||||
public static DiskInfo[] GetDockerMerge()
|
||||
{
|
||||
return DriveInfo.GetDrives()
|
||||
.Where(x => x.DriveFormat.Equals("overlay", StringComparison.OrdinalIgnoreCase) && x.DriveFormat.Contains("docker"))
|
||||
.Select(x => new DiskInfo(x)).ToArray();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 筛选出真正能够使用的磁盘
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static DiskInfo[] GetRealDisk()
|
||||
{
|
||||
var disks = DriveInfo.GetDrives()
|
||||
.Where(x =>
|
||||
x.DriveType == DriveType.Fixed &&
|
||||
x.TotalSize != 0 && x.DriveFormat != "overlay");
|
||||
|
||||
return disks.Select(x => new DiskInfo(x))
|
||||
.Distinct(new DiskInfoEquality()).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 筛选重复项
|
||||
/// </summary>
|
||||
private class DiskInfoEquality : IEqualityComparer<DiskInfo>
|
||||
{
|
||||
public bool Equals(DiskInfo x, DiskInfo y)
|
||||
{
|
||||
return x?.Id == y?.Id;
|
||||
}
|
||||
|
||||
public int GetHashCode(DiskInfo obj)
|
||||
{
|
||||
return obj.Id.GetHashCode();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
54
常用工具集/Utility/CZGL.SystemInfo/Memory/LinuxMemory.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using CZGL.SystemInfo.Memory;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public partial class LinuxMemory
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static MemoryValue GetMemory()
|
||||
{
|
||||
Sysinfo info = new Sysinfo();
|
||||
if (sysinfo(ref info) != 0)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
var usedPercentage = (((double)info.totalram - info.freeram) / (double)info.totalram) * 100;
|
||||
MemoryValue value = new MemoryValue(info.totalram, info.freeram, (ulong)usedPercentage, info.totalswap, info.freeswap);
|
||||
return value;
|
||||
}
|
||||
|
||||
#if NET7_0_OR_GREATER
|
||||
|
||||
/// <summary>
|
||||
/// 返回整个系统统计信息,<see href="https://linux.die.net/man/2/sysinfo"/>
|
||||
/// </summary>
|
||||
/// <remarks>int sysinfo(struct sysinfo *info);</remarks>
|
||||
/// <param name="info"></param>
|
||||
/// <returns></returns>
|
||||
[LibraryImport("libc.so.6", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.I4)]
|
||||
public static partial System.Int32 sysinfo(ref Sysinfo info);
|
||||
|
||||
#else
|
||||
|
||||
/// <summary>
|
||||
/// 返回整个系统统计信息,<see href="https://linux.die.net/man/2/sysinfo"/>
|
||||
/// </summary>
|
||||
/// <remarks>int sysinfo(struct sysinfo *info);</remarks>
|
||||
/// <param name="info"></param>
|
||||
/// <returns></returns>
|
||||
[DllImport("libc.so.6", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.I4)]
|
||||
public static extern System.Int32 sysinfo(ref Sysinfo info);
|
||||
|
||||
#endif
|
||||
}
|
||||
}
|
||||
17
常用工具集/Utility/CZGL.SystemInfo/Memory/MEMORYSTATUS.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public struct MEMORYSTATUS
|
||||
{
|
||||
public uint dwLength;
|
||||
public uint dwMemoryLoad;
|
||||
public uint dwTotalPhys;
|
||||
public uint dwAvailPhys;
|
||||
public uint dwTotalPageFile;
|
||||
public uint dwAvailPageFile;
|
||||
public uint dwTotalVirtual;
|
||||
public uint dwAvailVirtual;
|
||||
}
|
||||
}
|
||||
24
常用工具集/Utility/CZGL.SystemInfo/Memory/MemoryHelper.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static class MemoryHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前系统的内存信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static MemoryValue GetMemoryValue()
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
return WindowsMemory.GetMemory();
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
|
||||
return LinuxMemory.GetMemory();
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
68
常用工具集/Utility/CZGL.SystemInfo/Memory/MemoryStatusExE.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo.Memory
|
||||
{
|
||||
/// <summary>
|
||||
/// 包含有关物理内存和虚拟内存(包括扩展内存)的当前状态的信息。该 GlobalMemoryStatusEx在这个构造函数存储信息。
|
||||
/// <see ref="https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-memorystatusex"/>
|
||||
/// </summary>
|
||||
public struct MemoryStatusExE
|
||||
{
|
||||
/// <summary>
|
||||
/// 结构的大小,以字节为单位,必须在调用 GlobalMemoryStatusEx 之前设置此成员,可以用 Init 方法提前处理
|
||||
/// </summary>
|
||||
/// <remarks>应当使用本对象提供的 Init ,而不是使用构造函数!</remarks>
|
||||
public uint dwLength;
|
||||
|
||||
/// <summary>
|
||||
/// 一个介于 0 和 100 之间的数字,用于指定正在使用的物理内存的大致百分比(0 表示没有内存使用,100 表示内存已满)。
|
||||
/// </summary>
|
||||
public uint dwMemoryLoad;
|
||||
|
||||
/// <summary>
|
||||
/// 实际物理内存量,以字节为单位
|
||||
/// </summary>
|
||||
public ulong ullTotalPhys;
|
||||
|
||||
/// <summary>
|
||||
/// 当前可用的物理内存量,以字节为单位。这是可以立即重用而无需先将其内容写入磁盘的物理内存量。它是备用列表、空闲列表和零列表的大小之和
|
||||
/// </summary>
|
||||
public ulong ullAvailPhys;
|
||||
|
||||
/// <summary>
|
||||
/// 系统或当前进程的当前已提交内存限制,以字节为单位,以较小者为准。要获得系统范围的承诺内存限制,请调用GetPerformanceInfo
|
||||
/// </summary>
|
||||
public ulong ullTotalPageFile;
|
||||
|
||||
/// <summary>
|
||||
/// 当前进程可以提交的最大内存量,以字节为单位。该值等于或小于系统范围的可用提交值。要计算整个系统的可承诺值,调用GetPerformanceInfo核减价值CommitTotal从价值CommitLimit
|
||||
/// </summary>
|
||||
|
||||
public ulong ullAvailPageFile;
|
||||
|
||||
/// <summary>
|
||||
/// 调用进程的虚拟地址空间的用户模式部分的大小,以字节为单位。该值取决于进程类型、处理器类型和操作系统的配置。例如,对于 x86 处理器上的大多数 32 位进程,此值约为 2 GB,对于在启用4 GB 调整的系统上运行的具有大地址感知能力的 32 位进程约为 3 GB 。
|
||||
/// </summary>
|
||||
|
||||
public ulong ullTotalVirtual;
|
||||
|
||||
/// <summary>
|
||||
/// 当前在调用进程的虚拟地址空间的用户模式部分中未保留和未提交的内存量,以字节为单位
|
||||
/// </summary>
|
||||
public ulong ullAvailVirtual;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 预订的。该值始终为 0
|
||||
/// </summary>
|
||||
public ulong ullAvailExtendedVirtual;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public void Init()
|
||||
{
|
||||
dwLength = checked((uint)Marshal.SizeOf(typeof(MemoryStatusExE)));
|
||||
}
|
||||
}
|
||||
}
|
||||
66
常用工具集/Utility/CZGL.SystemInfo/Memory/MemoryValue.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 内存值表示
|
||||
/// </summary>
|
||||
public struct MemoryValue
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="totalPhysicalMemory">物理内存字节数</param>
|
||||
/// <param name="availablePhysicalMemory">可用的物理内存字节数</param>
|
||||
/// <param name="usedPercentage">已用物理内存百分比</param>
|
||||
/// <param name="totalVirtualMemory">虚拟内存字节数</param>
|
||||
/// <param name="availableVirtualMemory">可用虚拟内存字节数</param>
|
||||
public MemoryValue(
|
||||
ulong totalPhysicalMemory,
|
||||
ulong availablePhysicalMemory,
|
||||
double usedPercentage,
|
||||
ulong totalVirtualMemory,
|
||||
ulong availableVirtualMemory)
|
||||
{
|
||||
TotalPhysicalMemory = totalPhysicalMemory;
|
||||
AvailablePhysicalMemory = availablePhysicalMemory;
|
||||
UsedPercentage = usedPercentage;
|
||||
TotalVirtualMemory = totalVirtualMemory;
|
||||
AvailableVirtualMemory = availableVirtualMemory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 物理内存字节数
|
||||
/// </summary>
|
||||
public ulong TotalPhysicalMemory { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 可用的物理内存字节数
|
||||
/// </summary>
|
||||
public ulong AvailablePhysicalMemory { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已用物理内存字节数
|
||||
/// </summary>
|
||||
public ulong UsedPhysicalMemory => TotalPhysicalMemory - AvailablePhysicalMemory;
|
||||
|
||||
/// <summary>
|
||||
/// 已用物理内存百分比,0~100,100表示内存已用尽
|
||||
/// </summary>
|
||||
public double UsedPercentage { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 虚拟内存字节数
|
||||
/// </summary>
|
||||
public ulong TotalVirtualMemory { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 可用虚拟内存字节数
|
||||
/// </summary>
|
||||
public ulong AvailableVirtualMemory { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 已用虚拟内存字节数
|
||||
/// </summary>
|
||||
public ulong UsedVirtualMemory => TotalVirtualMemory - AvailableVirtualMemory;
|
||||
}
|
||||
|
||||
}
|
||||
74
常用工具集/Utility/CZGL.SystemInfo/Memory/Sysinfo.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public struct Sysinfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Seconds since boot
|
||||
/// </summary>
|
||||
public long uptime;
|
||||
|
||||
/// <summary>
|
||||
/// 获取 1,5,15 分钟内存的平均使用量,数组大小为 3
|
||||
/// </summary>
|
||||
unsafe public fixed ulong loads[3];
|
||||
/// <summary>
|
||||
/// 总物理内存
|
||||
/// </summary>
|
||||
public ulong totalram;
|
||||
|
||||
/// <summary>
|
||||
/// 可用内存
|
||||
/// </summary>
|
||||
public ulong freeram;
|
||||
|
||||
/// <summary>
|
||||
/// 共享内存
|
||||
/// </summary>
|
||||
public ulong sharedram;
|
||||
|
||||
/// <summary>
|
||||
/// Memory used by buffers
|
||||
/// </summary>
|
||||
public ulong bufferram;
|
||||
|
||||
/// <summary>
|
||||
/// Total swap space size
|
||||
/// </summary>
|
||||
public ulong totalswap;
|
||||
|
||||
/// <summary>
|
||||
/// swap space still available
|
||||
/// </summary>
|
||||
public ulong freeswap;
|
||||
|
||||
/// <summary>
|
||||
/// Number of current processes
|
||||
/// </summary>
|
||||
public ushort procs;
|
||||
|
||||
/// <summary>
|
||||
/// Total high memory size
|
||||
/// </summary>
|
||||
public ulong totalhigh;
|
||||
|
||||
/// <summary>
|
||||
/// Available high memory size
|
||||
/// </summary>
|
||||
public ulong freehigh;
|
||||
|
||||
/// <summary>
|
||||
/// Memory unit size in bytes
|
||||
/// </summary>
|
||||
public uint mem_unit;
|
||||
|
||||
/// <summary>
|
||||
/// Padding to 64 bytes
|
||||
/// </summary>
|
||||
unsafe public fixed byte _f[64];
|
||||
}
|
||||
}
|
||||
86
常用工具集/Utility/CZGL.SystemInfo/Memory/WindowsMemory.cs
Normal file
@@ -0,0 +1,86 @@
|
||||
using CZGL.SystemInfo.Memory;
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public partial class WindowsMemory
|
||||
{
|
||||
|
||||
#if NET7_0_OR_GREATER
|
||||
|
||||
/// <summary>
|
||||
/// 在内存超过 4 GB 的计算机上, GlobalMemoryStatus函数可能返回不正确的信息,报告值 –1 表示溢出。因此,应用程序应改用 GlobalMemoryStatusEx函数。
|
||||
/// </summary>
|
||||
/// <remarks>Windows XP [仅限桌面应用程序];最低支持服务器 Windows Server 2003 [仅限桌面应用程序]</remarks>
|
||||
/// <param name="lpBuffer"></param>
|
||||
[LibraryImport("Kernel32.dll", SetLastError = true)]
|
||||
public static partial void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);
|
||||
|
||||
/// <summary>
|
||||
/// 检索有关系统当前使用物理和虚拟内存的信息
|
||||
/// </summary>
|
||||
/// <remarks><see href="https://docs.microsoft.com/zh-cn/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex"/></remarks>
|
||||
/// <param name="lpBuffer"></param>
|
||||
/// <returns></returns>
|
||||
[LibraryImport("Kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial Boolean GlobalMemoryStatusEx(ref MemoryStatusExE lpBuffer);
|
||||
|
||||
#else
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 在内存超过 4 GB 的计算机上, GlobalMemoryStatus函数可能返回不正确的信息,报告值 –1 表示溢出。因此,应用程序应改用 GlobalMemoryStatusEx函数。
|
||||
/// </summary>
|
||||
/// <remarks>Windows XP [仅限桌面应用程序];最低支持服务器 Windows Server 2003 [仅限桌面应用程序]</remarks>
|
||||
/// <param name="lpBuffer"></param>
|
||||
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
public static extern void GlobalMemoryStatus(ref MEMORYSTATUS lpBuffer);
|
||||
|
||||
/// <summary>
|
||||
/// 检索有关系统当前使用物理和虚拟内存的信息
|
||||
/// </summary>
|
||||
/// <remarks><see href="https://docs.microsoft.com/zh-cn/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex"/></remarks>
|
||||
/// <param name="lpBuffer"></param>
|
||||
/// <returns></returns>
|
||||
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern Boolean GlobalMemoryStatusEx(ref MemoryStatusExE lpBuffer);
|
||||
#endif
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static MemoryValue GetMemory()
|
||||
{
|
||||
// 检查 Windows 内核版本,是否为旧系统
|
||||
if (Environment.OSVersion.Version.Major < 5)
|
||||
{
|
||||
// https://en.wikipedia.org/wiki/List_of_Microsoft_Windows_versions");
|
||||
return default;
|
||||
}
|
||||
|
||||
MemoryStatusExE memoryStatusEx = new MemoryStatusExE();
|
||||
// 初始化结构的大小
|
||||
memoryStatusEx.Init();
|
||||
// 刷新值
|
||||
if (!GlobalMemoryStatusEx(ref memoryStatusEx)) return default;
|
||||
|
||||
var TotalPhysicalMemory = memoryStatusEx.ullTotalPhys;
|
||||
var AvailablePhysicalMemory = memoryStatusEx.ullAvailPhys;
|
||||
var TotalVirtualMemory = memoryStatusEx.ullTotalVirtual;
|
||||
var AvailableVirtualMemory = memoryStatusEx.ullAvailVirtual;
|
||||
var UsedPercentage = memoryStatusEx.dwMemoryLoad;
|
||||
return new MemoryValue(
|
||||
TotalPhysicalMemory,
|
||||
AvailablePhysicalMemory,
|
||||
UsedPercentage,
|
||||
TotalVirtualMemory,
|
||||
AvailableVirtualMemory);
|
||||
}
|
||||
}
|
||||
}
|
||||
231
常用工具集/Utility/CZGL.SystemInfo/Network/NetworkInfo.cs
Normal file
@@ -0,0 +1,231 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 网络接口信息
|
||||
/// </summary>
|
||||
public class NetworkInfo
|
||||
{
|
||||
private NetworkInterface _instance;
|
||||
|
||||
private NetworkInfo(NetworkInterface network)
|
||||
{
|
||||
_instance = network;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当前实例使用的网络接口
|
||||
/// </summary>
|
||||
public NetworkInterface NetworkInterface => _instance;
|
||||
|
||||
|
||||
#region 基础信息
|
||||
|
||||
/// <summary>
|
||||
/// 获取网络适配器的标识符
|
||||
/// </summary>
|
||||
/// <remarks>ex:{92D3E528-5363-43C7-82E8-D143DC6617ED}</remarks>
|
||||
public string Id => _instance.Id;
|
||||
|
||||
/// <summary>
|
||||
/// 网络的 Mac 地址
|
||||
/// </summary>
|
||||
/// <remarks>ex: 1C997AF108E3</remarks>
|
||||
public string Mac => _instance.GetPhysicalAddress().ToString();
|
||||
|
||||
/// <summary>
|
||||
/// 网卡名称
|
||||
/// </summary>
|
||||
/// <remarks>ex:以太网,WLAN</remarks>
|
||||
public string Name => _instance.Name;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 描述网络接口的用户可读文本,
|
||||
/// 在 Windows 上,它通常描述接口供应商、类型 (例如,以太网) 、品牌和型号;
|
||||
/// </summary>
|
||||
/// <remarks>ex:Realtek PCIe GbE Family Controller、 Realtek 8822CE Wireless LAN 802.11ac PCI-E NIC</remarks>
|
||||
public string Trademark => _instance.Description;
|
||||
|
||||
/// <summary>
|
||||
/// 获取网络连接的当前操作状态<br />
|
||||
/// </summary>
|
||||
public OperationalStatus Status => _instance.OperationalStatus;
|
||||
|
||||
/// <summary>
|
||||
/// 获取网卡接口类型<br />
|
||||
/// </summary>
|
||||
public NetworkInterfaceType NetworkType => _instance.NetworkInterfaceType;
|
||||
|
||||
/// <summary>
|
||||
/// 网卡链接速度,每字节/秒为单位
|
||||
/// </summary>
|
||||
/// <remarks>如果是-1,则说明无法获取此网卡的链接速度;例如 270_000_000 表示是 270MB 的链接速度</remarks>
|
||||
public long Speed => _instance.Speed;
|
||||
|
||||
/// <summary>
|
||||
/// 是否支持 Ipv4
|
||||
/// </summary>
|
||||
public bool IsSupportIpv4 => _instance.Supports(NetworkInterfaceComponent.IPv4);
|
||||
|
||||
/// <summary>
|
||||
/// 获取分配给此接口的任意广播 IP 地址。只支持 Windows
|
||||
/// </summary>
|
||||
/// <remarks>一般情况下为空数组</remarks>
|
||||
public IPAddress[] AnycastAddresses
|
||||
{
|
||||
get
|
||||
{
|
||||
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
return _instance.GetIPProperties().AnycastAddresses.Select(x => x.Address).ToArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
return Array.Empty<IPAddress>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取分配给此接口的多播地址,ipv4、ipv6
|
||||
/// </summary>
|
||||
/// <remarks>ex:ff01::1%9 ff02::1%9<br />
|
||||
/// ff02::fb%9<br />
|
||||
/// ff02::1:3%9<br />
|
||||
/// ff02::1:ff61:9ae7%9<br />
|
||||
/// 224.0.0.1</remarks>
|
||||
public IPAddress[] MulticastAddresses => _instance.GetIPProperties().MulticastAddresses.Select(x => x.Address).ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// 获取分配给此接口的单播地址,ipv4、ipv6
|
||||
/// </summary>
|
||||
/// <remarks>ex:192.168.3.38</remarks>
|
||||
public IPAddress[] UnicastAddresses => _instance.GetIPProperties().UnicastAddresses.Select(x => x.Address).ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// 获取此接口的 IPv4 网关地址,ipv4、ipv6
|
||||
/// </summary>
|
||||
/// <remarks>ex:fe80::1677:40ff:fef9:bf95%5、192.168.3.1</remarks>
|
||||
public IPAddress[] GatewayAddresses => _instance.GetIPProperties().GatewayAddresses.Select(x => x.Address).ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// 获取此接口的域名系统 (DNS) 服务器的地址,ipv4、ipv6
|
||||
/// </summary>
|
||||
/// <remarks>ex:fe80::1677:40ff:fef9:bf95%5、192.168.3.1</remarks>
|
||||
public IPAddress[] DnsAddresses => _instance.GetIPProperties().DnsAddresses.ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// 是否支持 Ipv6
|
||||
/// </summary>
|
||||
public bool IsSupportIpv6 => _instance.Supports(NetworkInterfaceComponent.IPv6);
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 当前主机是否能够与其他计算机通讯(公网或内网),如果任何网络接口标记为 "up" 且不是环回或隧道接口,则认为网络连接可用。
|
||||
/// </summary>
|
||||
public static bool GetIsNetworkAvailable => NetworkInterface.GetIsNetworkAvailable();
|
||||
|
||||
/// <summary>
|
||||
/// 计算 IPV4 的网络流量
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotSupportedException">当前网卡不支持 IPV4</exception>
|
||||
public Rate GetIpv4Speed()
|
||||
{
|
||||
// 当前网卡不支持 IPV4
|
||||
if (!IsSupportIpv4) return default;
|
||||
var ipv4Statistics = _instance.GetIPv4Statistics();
|
||||
var speed = new Rate(DateTime.Now, ipv4Statistics.BytesReceived, ipv4Statistics.BytesSent);
|
||||
return speed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算 IPV4 、IPV6 的网络流量
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Rate IpvSpeed()
|
||||
{
|
||||
var ipvStatistics = _instance.GetIPStatistics();
|
||||
var speed = new Rate(DateTime.Now, ipvStatistics.BytesReceived, ipvStatistics.BytesSent);
|
||||
return speed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有 IP 地址
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static IPAddress[] GetIPAddresses()
|
||||
{
|
||||
var hostName = Dns.GetHostName();
|
||||
return Dns.GetHostAddresses(hostName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前真实 IP
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static IPAddress TryGetRealIpv4()
|
||||
{
|
||||
var addrs = GetIPAddresses();
|
||||
var ipv4 = addrs.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);
|
||||
return ipv4;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取真实网卡
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static NetworkInfo TryGetRealNetworkInfo()
|
||||
{
|
||||
var realIp = TryGetRealIpv4();
|
||||
if (realIp == null)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
var infos = NetworkInfo.GetNetworkInfos().ToArray();
|
||||
var info = infos.FirstOrDefault(x => x.UnicastAddresses.Any(i => i.MapToIPv4().ToString() == realIp.MapToIPv4().ToString()));
|
||||
if (info == null)
|
||||
{
|
||||
return default;
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取此主机中所有网卡接口
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static NetworkInfo[] GetNetworkInfos()
|
||||
{
|
||||
return NetworkInterface.GetAllNetworkInterfaces().Select(x => new NetworkInfo(x)).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算网络流量速率
|
||||
/// </summary>
|
||||
/// <param name="oldRate"></param>
|
||||
/// <param name="newRate"></param>
|
||||
/// <returns></returns>
|
||||
public static (SizeInfo Received, SizeInfo Sent) GetSpeed(Rate oldRate, Rate newRate)
|
||||
{
|
||||
var receive = newRate.ReceivedLength - oldRate.ReceivedLength;
|
||||
var send = newRate.SendLength - oldRate.SendLength;
|
||||
var interval = Math.Round((newRate.StartTime - oldRate.StartTime).TotalSeconds, 2);
|
||||
|
||||
long rSpeed = (long)(receive / interval);
|
||||
long sSpeed = (long)(send / interval);
|
||||
|
||||
return (SizeInfo.Get(rSpeed), SizeInfo.Get(sSpeed));
|
||||
}
|
||||
}
|
||||
}
|
||||
34
常用工具集/Utility/CZGL.SystemInfo/Network/Rate.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public struct Rate
|
||||
{
|
||||
public Rate(DateTime startTime, long receivedLength, long sendLength)
|
||||
{
|
||||
StartTime = startTime;
|
||||
ReceivedLength = receivedLength;
|
||||
SendLength = sendLength;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 记录时间
|
||||
/// </summary>
|
||||
public DateTime StartTime { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 此网卡总接收网络流量字节数
|
||||
/// </summary>
|
||||
public long ReceivedLength { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 此网卡总发送网络流量字节数
|
||||
/// </summary>
|
||||
public long SendLength { get; private set; }
|
||||
}
|
||||
|
||||
}
|
||||
61
常用工具集/Utility/CZGL.SystemInfo/SizeInfo.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 大小信息
|
||||
/// </summary>
|
||||
public struct SizeInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Byte 长度
|
||||
/// </summary>
|
||||
public long ByteLength { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 大小
|
||||
/// </summary>
|
||||
public decimal Size { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 单位
|
||||
/// </summary>
|
||||
public UnitType SizeType { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 将字节单位转换为合适的单位
|
||||
/// </summary>
|
||||
/// <param name="byteLength">字节长度</param>
|
||||
/// <returns></returns>
|
||||
public static SizeInfo Get(long byteLength)
|
||||
{
|
||||
UnitType unit = 0;
|
||||
decimal number = byteLength;
|
||||
if (byteLength < 1000)
|
||||
{
|
||||
return new SizeInfo()
|
||||
{
|
||||
ByteLength = byteLength,
|
||||
Size = byteLength,
|
||||
SizeType = UnitType.B
|
||||
};
|
||||
}
|
||||
// 避免出现 1023B 这种情况;这样 1023B 会显示 0.99KB
|
||||
while (Math.Round(number / 1000) >= 1)
|
||||
{
|
||||
number = number / 1024;
|
||||
unit++;
|
||||
}
|
||||
|
||||
return new SizeInfo
|
||||
{
|
||||
Size = Math.Round(number, 2),
|
||||
SizeType = unit,
|
||||
ByteLength = byteLength
|
||||
};
|
||||
|
||||
throw new Exception();
|
||||
}
|
||||
}
|
||||
}
|
||||
133
常用工具集/Utility/CZGL.SystemInfo/System/SystemPlatformInfo.cs
Normal file
@@ -0,0 +1,133 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 提供有关 .NET 运行时安装的信息、程序系统信息等。
|
||||
/// </summary>
|
||||
public static class SystemPlatformInfo
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// .NET Fx/Core Runtime version
|
||||
/// <para>ex: .NET Core 3.1.9</para>
|
||||
/// </summary>
|
||||
public static string FrameworkDescription => RuntimeInformation.FrameworkDescription;
|
||||
|
||||
/// <summary>
|
||||
/// .NET Fx/Core version
|
||||
/// <para>
|
||||
/// ex:<br />
|
||||
/// 3.1.9
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string FrameworkVersion => Environment.Version.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// 操作系统平台架构,可点击 <see cref="Architecture" /> 获取详细的信息
|
||||
/// <para>
|
||||
/// ex:<br />
|
||||
/// X86<br />
|
||||
/// X64<br />
|
||||
/// Arm<br />
|
||||
/// Arm64
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string OSArchitecture => RuntimeInformation.OSArchitecture.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// 获取操作系统的类型 <see cref="PlatformID"/>
|
||||
/// <para>
|
||||
/// ex:<br />
|
||||
/// Win32S、Win32Windows、Win32NT、WinCE、Unix、Xbox、MacOSX
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string OSPlatformID => Environment.OSVersion.Platform.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// 操作系统内核版本
|
||||
/// <para>
|
||||
/// ex:<br />
|
||||
/// Microsoft Windows NT 6.2.9200.0<br />
|
||||
/// Unix 4.4.0.19041
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string OSVersion => Environment.OSVersion.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// 操作系统的版本描述
|
||||
/// <para>
|
||||
/// ex: <br />
|
||||
/// Microsoft Windows 10.0.19041
|
||||
/// <br />
|
||||
/// Linux 4.4.0-19041-Microsoft #488-Microsoft Mon Sep 01 13:43:00 PST 2020
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string OSDescription => RuntimeInformation.OSDescription;
|
||||
|
||||
/// <summary>
|
||||
/// 本进程的架构,可点击 <see cref="Architecture" /> 获取详细的信息
|
||||
/// <para>
|
||||
/// ex:<br />
|
||||
/// X86<br />
|
||||
/// X64<br />
|
||||
/// Arm<br />
|
||||
/// Arm64
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string ProcessArchitecture => RuntimeInformation.ProcessArchitecture.ToString();
|
||||
|
||||
/// <summary>
|
||||
/// 当前计算机上的处理器数
|
||||
/// </summary>
|
||||
/// <remarks>如 4核心8线程的 CPU,这里会获取到 8</remarks>
|
||||
public static int ProcessorCount => Environment.ProcessorCount;
|
||||
|
||||
/// <summary>
|
||||
/// 计算机名称
|
||||
/// </summary>
|
||||
public static string MachineName => Environment.MachineName;
|
||||
|
||||
/// <summary>
|
||||
/// 当前登录到此系统的用户名称
|
||||
/// </summary>
|
||||
public static string UserName => Environment.UserName;
|
||||
|
||||
/// <summary>
|
||||
/// 用户网络域名称,即 hostname
|
||||
/// </summary>
|
||||
public static string UserDomainName => Environment.UserDomainName;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 是否在交互模式中运行
|
||||
/// </summary>
|
||||
public static bool IsUserInteractive => Environment.UserInteractive;
|
||||
|
||||
/// <summary>
|
||||
/// 系统的磁盘和分区列表
|
||||
/// <para>
|
||||
/// ex:<br />
|
||||
/// Windows: D:\, E:\, F:\, G:\, H:\, J:\, X:\<br />
|
||||
/// Linux: /, /dev, /sys, /proc, /dev/pts, /run, /run/lock, /run/shm ...
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string[] GetLogicalDrives => Environment.GetLogicalDrives();
|
||||
|
||||
/// <summary>
|
||||
/// 系统根目录完全路径。<b>Linux 没有系统根目录</b>
|
||||
/// <para>
|
||||
/// ex:<br />
|
||||
/// Windows: X:\WINDOWS\system32<br></br>
|
||||
/// Linux : null
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string SystemDirectory => Environment.SystemDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// 操作系统内存页一页的字节数
|
||||
/// </summary>
|
||||
public static int MemoryPageSize => Environment.SystemPageSize;
|
||||
}
|
||||
}
|
||||
38
常用工具集/Utility/CZGL.SystemInfo/UnitType.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
namespace CZGL.SystemInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 单位
|
||||
/// </summary>
|
||||
public enum UnitType : int
|
||||
{
|
||||
/// <summary>
|
||||
/// Byte
|
||||
/// </summary>
|
||||
///
|
||||
B = 0,
|
||||
/// <summary>
|
||||
/// KB
|
||||
/// </summary>
|
||||
KB,
|
||||
|
||||
/// <summary>
|
||||
/// MB
|
||||
/// </summary>
|
||||
MB,
|
||||
|
||||
/// <summary>
|
||||
/// GB
|
||||
/// </summary>
|
||||
GB,
|
||||
|
||||
/// <summary>
|
||||
/// TB
|
||||
/// </summary>
|
||||
TB,
|
||||
|
||||
/// <summary>
|
||||
/// PB
|
||||
/// </summary>
|
||||
PB
|
||||
}
|
||||
}
|
||||
394
常用工具集/Utility/Core/Checker.cs
Normal file
@@ -0,0 +1,394 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
public static class Checker
|
||||
{
|
||||
#region 验证IP
|
||||
/// <summary>
|
||||
/// 验证IP
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsIP(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
public static bool HasIP(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证EMail是否合法
|
||||
/// <summary>
|
||||
/// 验证EMail是否合法
|
||||
/// </summary>
|
||||
/// <param name="email">要验证的Email</param>
|
||||
public static bool IsEmail(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
public static bool HasEmail(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证网址
|
||||
/// <summary>
|
||||
/// 验证网址
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsUrl(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
public static bool HasUrl(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证日期
|
||||
/// <summary>
|
||||
/// 验证日期
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsDateTime(this string source)
|
||||
{
|
||||
try
|
||||
{
|
||||
DateTime time = Convert.ToDateTime(source);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region 验证手机号
|
||||
/// <summary>
|
||||
/// 验证手机号
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsMobile(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"^1[35678]\d{9}$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
public static bool HasMobile(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"1[35678]\d{9}", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证身份证是否有效
|
||||
/// <summary>
|
||||
/// 验证身份证是否有效
|
||||
/// </summary>
|
||||
/// <param name="Id"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsIDCard(this string Id)
|
||||
{
|
||||
if (Id.Length == 18)
|
||||
{
|
||||
bool check = IsIDCard18(Id);
|
||||
return check;
|
||||
}
|
||||
else if (Id.Length == 15)
|
||||
{
|
||||
bool check = IsIDCard15(Id);
|
||||
return check;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public static bool IsIDCard18(this string Id)
|
||||
{
|
||||
long n = 0;
|
||||
if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
|
||||
{
|
||||
return false;//数字验证
|
||||
}
|
||||
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
|
||||
if (address.IndexOf(Id.Remove(2)) == -1)
|
||||
{
|
||||
return false;//省份验证
|
||||
}
|
||||
string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
|
||||
DateTime time = new DateTime();
|
||||
if (DateTime.TryParse(birth, out time) == false)
|
||||
{
|
||||
return false;//生日验证
|
||||
}
|
||||
string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
|
||||
string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
|
||||
char[] Ai = Id.Remove(17).ToCharArray();
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 17; i++)
|
||||
{
|
||||
sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
|
||||
}
|
||||
int y = -1;
|
||||
Math.DivRem(sum, 11, out y);
|
||||
if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
|
||||
{
|
||||
return false;//校验码验证
|
||||
}
|
||||
return true;//符合GB11643-1999标准
|
||||
}
|
||||
public static bool IsIDCard15(this string Id)
|
||||
{
|
||||
long n = 0;
|
||||
if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
|
||||
{
|
||||
return false;//数字验证
|
||||
}
|
||||
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
|
||||
if (address.IndexOf(Id.Remove(2)) == -1)
|
||||
{
|
||||
return false;//省份验证
|
||||
}
|
||||
string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
|
||||
DateTime time = new DateTime();
|
||||
if (DateTime.TryParse(birth, out time) == false)
|
||||
{
|
||||
return false;//生日验证
|
||||
}
|
||||
return true;//符合15位身份证标准
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
|
||||
#region 是不是Int型的
|
||||
/// <summary>
|
||||
/// 是不是Int型的
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsInt(this string source)
|
||||
{
|
||||
Regex regex = new Regex(@"^(-){0,1}\d+$");
|
||||
if (regex.Match(source).Success)
|
||||
{
|
||||
if ((long.Parse(source) > 0x7fffffffL) || (long.Parse(source) < -2147483648L))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 看字符串的长度是不是在限定数之间 一个中文为两个字符
|
||||
/// <summary>
|
||||
/// 看字符串的长度是不是在限定数之间 一个中文为两个字符
|
||||
/// </summary>
|
||||
/// <param name="source">字符串</param>
|
||||
/// <param name="begin">大于等于</param>
|
||||
/// <param name="end">小于等于</param>
|
||||
/// <returns></returns>
|
||||
public static bool IsLengthStr(this string source, int begin, int end)
|
||||
{
|
||||
int length = Regex.Replace(source, @"[^\x00-\xff]", "OK").Length;
|
||||
if ((length <= begin) && (length >= end))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 是不是中国电话,格式010-85849685
|
||||
/// <summary>
|
||||
/// 是不是中国电话,格式010-85849685
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsTel(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"^\d{3,4}-?\d{6,8}$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 邮政编码 6个数字
|
||||
/// <summary>
|
||||
/// 邮政编码 6个数字
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsPostCode(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"^\d{6}$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
#region 中文
|
||||
/// <summary>
|
||||
/// 中文
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsChinese(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"^[\u4e00-\u9fa5]+$", RegexOptions.IgnoreCase);
|
||||
}
|
||||
public static bool hasChinese(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"[\u4e00-\u9fa5]+", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证是不是正常字符 字母,数字,下划线的组合
|
||||
/// <summary>
|
||||
/// 验证是不是正常字符 字母,数字,下划线的组合
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsNormalChar(this string source)
|
||||
{
|
||||
return Regex.IsMatch(source, @"[\w\d_]+", RegexOptions.IgnoreCase);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 验证用户名:必须以字母开头,可以包含字母、数字、“_”、“.”,至少5个字符
|
||||
/// <summary>
|
||||
/// 验证用户名:必须以字母开头,可以包含字母、数字、“_”、“.”,至少5个字符
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static bool checkUserId(this string str)
|
||||
{
|
||||
Regex regex = new Regex("[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}");
|
||||
if (regex.Match(str).Success)
|
||||
if (regex.Matches(str)[0].Value.Length == str.Length)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 是否是Base64字符串
|
||||
/// </summary>
|
||||
/// <param name="eStr"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsBase64(string eStr)
|
||||
{
|
||||
if ((eStr.Length % 4) != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (!Regex.IsMatch(eStr, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#region 验证是否为小数
|
||||
public static bool IsValidDecimal(this string strIn)
|
||||
{
|
||||
return Regex.IsMatch(strIn, @"[0].d{1,2}|[1]");
|
||||
}
|
||||
#endregion
|
||||
#region 验证年月日
|
||||
public static bool IsValidDate(this string strIn)
|
||||
{
|
||||
return Regex.IsMatch(strIn, @"^2d{3}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[1-2]d|3[0-1])(?:0?[1-9]|1d|2[0-3]):(?:0?[1-9]|[1-5]d):(?:0?[1-9]|[1-5]d)$");
|
||||
}
|
||||
#endregion
|
||||
#region 验证日期格式
|
||||
//检察是否正确的日期格式
|
||||
public static bool IsDate(this string str)
|
||||
{
|
||||
//考虑到了4年一度的366天,还有特殊的2月的日期
|
||||
Regex reg = new Regex(@"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$");
|
||||
return reg.IsMatch(str);
|
||||
}
|
||||
#endregion
|
||||
#region 验证后缀名
|
||||
public static bool IsValidPostfix(this string strIn)
|
||||
{
|
||||
return Regex.IsMatch(strIn, @".(?i:gif|jpg)$");
|
||||
}
|
||||
#endregion
|
||||
#region 验证字符是否在4至12之间
|
||||
public static bool IsValidByte(this string strIn)
|
||||
{
|
||||
return Regex.IsMatch(strIn, @"^[a-z]{4,12}$");
|
||||
}
|
||||
#endregion
|
||||
#region 判断字符串是否为数字
|
||||
/// <summary>
|
||||
/// 判断字符串是否为数字
|
||||
/// </summary>
|
||||
/// <param name="str">待验证的字符窜</param>
|
||||
/// <returns>bool</returns>
|
||||
public static bool IsNumber(this string str)
|
||||
{
|
||||
bool result = true;
|
||||
foreach (char ar in str)
|
||||
{
|
||||
if (!char.IsNumber(ar))
|
||||
{
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endregion
|
||||
#region 是否为数字型
|
||||
/// <summary>
|
||||
/// 是否为数字型
|
||||
/// </summary>
|
||||
/// <param name="strNumber"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsDecimal(this string strNumber)
|
||||
{
|
||||
return new System.Text.RegularExpressions.Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber);
|
||||
}
|
||||
#endregion
|
||||
#region 验证是否包含汉语/全部汉语
|
||||
/// <summary>
|
||||
/// 验证是否包含汉语
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsHanyu(this string str)
|
||||
{
|
||||
Regex regex = new Regex("[\u4e00-\u9fa5]");
|
||||
if (regex.Match(str).Success)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// 验证是否全部汉语
|
||||
/// </summary>
|
||||
/// <param name="str"></param>
|
||||
/// <returns></returns>
|
||||
public static bool IsHanyuAll(this string str)
|
||||
{
|
||||
Regex regex = new Regex("[\u4e00-\u9fa5]");
|
||||
//匹配的内容长度和被验证的内容长度相同时,验证通过
|
||||
if (regex.Match(str).Success)
|
||||
if (regex.Matches(str).Count == str.Length)
|
||||
return true;
|
||||
//其它,未通过
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
464
常用工具集/Utility/Core/ChineseDateTime.cs
Normal file
@@ -0,0 +1,464 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// ChineseDateTime
|
||||
/// 一日有十二时辰,一时辰有四刻,一刻有三盏茶,一盏茶有两柱香
|
||||
/// 一柱香有五分,一分有六弹指,一弹指有十刹那,一刹那为一念
|
||||
/// </summary>
|
||||
public class ChineseDateTime
|
||||
{
|
||||
#region ====== 内部常量 ======
|
||||
private readonly ChineseLunisolarCalendar _chineseDateTime;
|
||||
private readonly DateTime _dateTime;
|
||||
private readonly int _serialMonth;
|
||||
|
||||
private static readonly string[] _chineseNumber = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
|
||||
private static readonly string[] _chineseMonth =
|
||||
{
|
||||
"正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "冬", "腊"
|
||||
};
|
||||
private static readonly string[] _chineseDay =
|
||||
{
|
||||
"初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
|
||||
"十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
|
||||
"廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
|
||||
};
|
||||
private static readonly string[] _chineseWeek =
|
||||
{
|
||||
"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"
|
||||
};
|
||||
|
||||
private static readonly string[] _celestialStem = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
|
||||
private static readonly string[] _terrestrialBranch = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
|
||||
private static readonly string[] _chineseZodiac = { "鼠", "牛", "虎", "免", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };
|
||||
|
||||
private static readonly string[] _solarTerm =
|
||||
{
|
||||
"小寒", "大寒", "立春", "雨水", "惊蛰", "春分",
|
||||
"清明", "谷雨", "立夏", "小满", "芒种", "夏至",
|
||||
"小暑", "大暑", "立秋", "处暑", "白露", "秋分",
|
||||
"寒露", "霜降", "立冬", "小雪", "大雪", "冬至"
|
||||
};
|
||||
private static readonly int[] _solarTermInfo = {
|
||||
0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989,
|
||||
308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758
|
||||
};
|
||||
#endregion
|
||||
|
||||
#region ======= 构建日期 ======
|
||||
|
||||
public ChineseDateTime(DateTime dateTime)
|
||||
{
|
||||
_chineseDateTime = new ChineseLunisolarCalendar();
|
||||
if (dateTime < _chineseDateTime.MinSupportedDateTime || dateTime > _chineseDateTime.MaxSupportedDateTime)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
$"参数日期不在有效的范围内:只支持{_chineseDateTime.MinSupportedDateTime.ToShortTimeString()}到{_chineseDateTime.MaxSupportedDateTime}");
|
||||
}
|
||||
|
||||
Year = _chineseDateTime.GetYear(dateTime);
|
||||
Month = _chineseDateTime.GetMonth(dateTime);
|
||||
Day = _chineseDateTime.GetDayOfMonth(dateTime);
|
||||
IsLeep = _chineseDateTime.IsLeapMonth(Year, Month);
|
||||
_dateTime = dateTime;
|
||||
_serialMonth = Month;
|
||||
var leepMonth = _chineseDateTime.GetLeapMonth(Year);
|
||||
if (leepMonth > 0 && leepMonth <= Month) Month--;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 参数为农历的年月日及是否润月
|
||||
/// </summary>
|
||||
/// <param name="year"></param>
|
||||
/// <param name="month"></param>
|
||||
/// <param name="day"></param>
|
||||
/// <param name="isLeap"></param>
|
||||
public ChineseDateTime(int year, int month, int day, bool isLeap = false)
|
||||
: this(year, month, day, 0, 0, 0, isLeap)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public ChineseDateTime(int year, int month, int day, int hour, int minute, int second, bool isLeap = false)
|
||||
: this(year, month, day, hour, minute, second, 0, isLeap)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public ChineseDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, bool isLeap = false)
|
||||
{
|
||||
_chineseDateTime = new ChineseLunisolarCalendar();
|
||||
if (year < _chineseDateTime.MinSupportedDateTime.Year || year >= _chineseDateTime.MaxSupportedDateTime.Year)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
$"参数年份不在有效的范围内,只支持{_chineseDateTime.MinSupportedDateTime.Year}到{_chineseDateTime.MaxSupportedDateTime.Year - 1}");
|
||||
}
|
||||
|
||||
if (month < 1 || month > 12) throw new ArgumentOutOfRangeException($"月份只支持1-12");
|
||||
IsLeep = isLeap;
|
||||
var leepMonth = _chineseDateTime.GetLeapMonth(year);
|
||||
if (leepMonth - 1 != month)
|
||||
IsLeep = false;
|
||||
_serialMonth = month;
|
||||
if (leepMonth > 0 && (month == leepMonth - 1 && isLeap || month > leepMonth - 1))
|
||||
_serialMonth = month + 1;
|
||||
|
||||
if (_chineseDateTime.GetDaysInMonth(year, _serialMonth) < day || day < 1)
|
||||
throw new ArgumentOutOfRangeException($"指定的月份天数,不在有效的范围内");
|
||||
|
||||
Year = year;
|
||||
Month = month;
|
||||
Day = day;
|
||||
_dateTime = _chineseDateTime.ToDateTime(Year, _serialMonth, Day, hour, minute, second, millisecond);
|
||||
}
|
||||
|
||||
public static ChineseDateTime Now => new ChineseDateTime(DateTime.Now);
|
||||
|
||||
#endregion
|
||||
|
||||
#region ====== 年月日润属性 ======
|
||||
public int Year { get; }
|
||||
public int Month { get; }
|
||||
public int Day { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否为润月
|
||||
/// </summary>
|
||||
public bool IsLeep { get; }
|
||||
#endregion
|
||||
|
||||
#region ====== 输出常规日期 ======
|
||||
/// <summary>
|
||||
/// 转换为公历
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public DateTime ToDateTime()
|
||||
{
|
||||
return _chineseDateTime.ToDateTime(Year, _serialMonth, Day, _dateTime.Hour,
|
||||
_dateTime.Minute,
|
||||
_dateTime.Second, _dateTime.Millisecond);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 短日期(农历)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string ToShortDateString()
|
||||
{
|
||||
return $"{Year}-{GetLeap(false)}{Month}-{Day}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 长日期(农历)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string ToLongDateString()
|
||||
{
|
||||
return $"{Year}年{GetLeap()}{Month}月-{Day}日";
|
||||
}
|
||||
|
||||
public new string ToString()
|
||||
{
|
||||
return $"{Year}-{GetLeap(false)}{Month}-{Day} {_dateTime.Hour}:{_dateTime.Minute}:{_dateTime.Second}";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ====== 输出中文日期及星期 ======
|
||||
public string ToChineseString()
|
||||
{
|
||||
return ToChineseString("yMd");
|
||||
}
|
||||
|
||||
public string GetChineseDate()
|
||||
{
|
||||
var date = new StringBuilder();
|
||||
date.Append(GetMonth() + "月");
|
||||
date.Append(GetDay() + "");
|
||||
date.AppendLine();
|
||||
date.Append(GetEraYear() + ChineseZodiac + "年");
|
||||
date.AppendLine();
|
||||
return date.ToString();
|
||||
}
|
||||
|
||||
public string ToChineseString(string format)
|
||||
{
|
||||
var year = GetYear();
|
||||
var month = GetMonth();
|
||||
var day = GetDay();
|
||||
|
||||
var date = new StringBuilder();
|
||||
foreach (var item in format.ToCharArray())
|
||||
{
|
||||
switch (item)
|
||||
{
|
||||
case 'y':
|
||||
date.Append($"{year}年");
|
||||
break;
|
||||
case 'M':
|
||||
date.Append($"{month}月");
|
||||
break;
|
||||
case 'd':
|
||||
date.Append($"{day}");
|
||||
break;
|
||||
default:
|
||||
date.Append(item);
|
||||
break;
|
||||
}
|
||||
}
|
||||
var def = $"{year}年{month}月{day}";
|
||||
var result = date.ToString();
|
||||
return string.IsNullOrEmpty(result) ? def : result;
|
||||
}
|
||||
|
||||
public string ChineseWeek => _chineseWeek[(int)_dateTime.DayOfWeek];
|
||||
#endregion
|
||||
|
||||
#region ====== 输出天干地支生肖 ======
|
||||
|
||||
public string ToChineseEraString()
|
||||
{
|
||||
return ToChineseEraString("yMdHm");
|
||||
}
|
||||
|
||||
public string ToChineseEraString(string format)
|
||||
{
|
||||
var year = GetEraYear();
|
||||
var month = GetEraMonth();
|
||||
var day = GetEraDay();
|
||||
var hour = GetEraHour();
|
||||
var minute = GetEraMinute();
|
||||
|
||||
var date = new StringBuilder();
|
||||
foreach (var item in format.ToCharArray())
|
||||
{
|
||||
switch (item)
|
||||
{
|
||||
case 'y':
|
||||
date.Append($"{year}年");
|
||||
break;
|
||||
case 'M':
|
||||
date.Append($"{month}月");
|
||||
break;
|
||||
case 'd':
|
||||
date.Append($"{day}日");
|
||||
break;
|
||||
case 'H':
|
||||
date.Append($"{hour}时");
|
||||
break;
|
||||
case 'm':
|
||||
date.Append($"{minute}刻");
|
||||
break;
|
||||
default:
|
||||
date.Append(item);
|
||||
break;
|
||||
}
|
||||
}
|
||||
var def = $"{year}年{month}月{day}日{hour}时";
|
||||
var result = date.ToString();
|
||||
return result.IsNullOrEmpty() ? def : result;
|
||||
}
|
||||
|
||||
public string ChineseZodiac => _chineseZodiac[(Year - 4) % 12];
|
||||
#endregion
|
||||
|
||||
#region ====== 辅助方法(Chinese) ======
|
||||
private string GetYear()
|
||||
{
|
||||
var yearArray = Array.ConvertAll(Year.ToString().ToCharArray(), x => int.Parse(x.ToString()));
|
||||
var year = new StringBuilder();
|
||||
foreach (var item in yearArray)
|
||||
year.Append(_chineseNumber[item]);
|
||||
return year.ToString();
|
||||
}
|
||||
|
||||
private string GetMonth()
|
||||
{
|
||||
return $"{GetLeap()}{_chineseMonth[Month - 1]}";
|
||||
}
|
||||
|
||||
private string GetDay()
|
||||
{
|
||||
return _chineseDay[Day - 1];
|
||||
}
|
||||
|
||||
private string GetLeap(bool isChinese = true)
|
||||
{
|
||||
return IsLeep ? isChinese ? "润" : "L" : "";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ====== 输助方法(天干地支)======
|
||||
//年采用的头尾法,月采用的是节令法,主流日历基本上都这种结合,如百度的日历
|
||||
|
||||
private string GetEraYear()
|
||||
{
|
||||
var sexagenaryYear = _chineseDateTime.GetSexagenaryYear(_dateTime);
|
||||
var stemIndex = _chineseDateTime.GetCelestialStem(sexagenaryYear) - 1;
|
||||
var branchIndex = _chineseDateTime.GetTerrestrialBranch(sexagenaryYear) - 1;
|
||||
return $"{_celestialStem[stemIndex]}{_terrestrialBranch[branchIndex]}";
|
||||
}
|
||||
|
||||
private string GetEraMonth()
|
||||
{
|
||||
#region ====== 节令法 ======
|
||||
var solarIndex = SolarTermFunc((x, y) => x <= y, out var dt);
|
||||
solarIndex = solarIndex == -1 ? 23 : solarIndex;
|
||||
var currentIndex = (int)Math.Floor(solarIndex / (decimal)2);
|
||||
|
||||
//天干
|
||||
var solarMonth = currentIndex == 0 ? 11 : currentIndex - 1; //计算天干序(月份)
|
||||
var sexagenaryYear = _chineseDateTime.GetSexagenaryYear(_dateTime);
|
||||
var stemYear = _chineseDateTime.GetCelestialStem(sexagenaryYear) - 1;
|
||||
if (solarMonth == 0) //立春时,春节前后的不同处理
|
||||
{
|
||||
var year = _chineseDateTime.GetYear(dt);
|
||||
var month = _chineseDateTime.GetMonth(dt);
|
||||
stemYear = year == Year && month != 1 ? stemYear + 1 : stemYear;
|
||||
}
|
||||
if (solarMonth == 11) //立春在春节后,对前一节气春节前后不同处理
|
||||
{
|
||||
var year = _chineseDateTime.GetYear(dt);
|
||||
stemYear = year != Year ? stemYear - 1 : stemYear;
|
||||
}
|
||||
int stemIndex;
|
||||
switch (stemYear)
|
||||
{
|
||||
case 0:
|
||||
case 5:
|
||||
stemIndex = 3;
|
||||
break;
|
||||
case 1:
|
||||
case 6:
|
||||
stemIndex = 5;
|
||||
break;
|
||||
case 2:
|
||||
case 7:
|
||||
stemIndex = 7;
|
||||
break;
|
||||
case 3:
|
||||
case 8:
|
||||
stemIndex = 9;
|
||||
break;
|
||||
default:
|
||||
stemIndex = 1;
|
||||
break;
|
||||
}
|
||||
//天干序
|
||||
stemIndex = (stemIndex - 1 + solarMonth) % 10;
|
||||
|
||||
//地支序
|
||||
var branchIndex = currentIndex >= 11 ? currentIndex - 11 : currentIndex + 1;
|
||||
|
||||
return $"{_celestialStem[stemIndex]}{_terrestrialBranch[branchIndex]}";
|
||||
|
||||
#endregion
|
||||
|
||||
#region ====== 头尾法 ======
|
||||
//这里算法要容易些,原理和节令法一样,只需取农历整年整月即可。未贴上来
|
||||
#endregion
|
||||
}
|
||||
|
||||
private string GetEraDay()
|
||||
{
|
||||
var ts = _dateTime - new DateTime(1901, 2, 15);
|
||||
var offset = ts.Days;
|
||||
var sexagenaryDay = offset % 60;
|
||||
return $"{_celestialStem[sexagenaryDay % 10]}{_terrestrialBranch[sexagenaryDay % 12]}";
|
||||
}
|
||||
|
||||
private string GetEraHour()
|
||||
{
|
||||
var hourIndex = (int)Math.Floor((_dateTime.Hour + 1) / (decimal)2);
|
||||
hourIndex = hourIndex == 12 ? 0 : hourIndex;
|
||||
return _terrestrialBranch[hourIndex];
|
||||
}
|
||||
|
||||
private string GetEraMinute()
|
||||
{
|
||||
var realMinute = (_dateTime.Hour % 2 == 0 ? 60 : 0) + _dateTime.Minute;
|
||||
return $"{_chineseNumber[(int)Math.Floor(realMinute / (decimal)30) + 1]}";
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region ====== 24节气 ======
|
||||
/// <summary>
|
||||
/// 当前节气,没有则返回空
|
||||
/// </summary>
|
||||
public string SolarTerm
|
||||
{
|
||||
get
|
||||
{
|
||||
var i = SolarTermFunc((x, y) => x == y, out var dt);
|
||||
return i == -1 ? "" : _solarTerm[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上一个节气
|
||||
/// </summary>
|
||||
public string SolarTermPrev
|
||||
{
|
||||
get
|
||||
{
|
||||
var i = SolarTermFunc((x, y) => x < y, out var dt);
|
||||
return i == -1 ? "" : _solarTerm[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 下一个节气
|
||||
/// </summary>
|
||||
public string SolarTermNext
|
||||
{
|
||||
get
|
||||
{
|
||||
var i = SolarTermFunc((x, y) => x > y, out var dt);
|
||||
return i == -1 ? "" : $"{_solarTerm[i]}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 节气计算(当前年),返回指定条件的节气序及日期(公历)
|
||||
/// </summary>
|
||||
/// <param name="func"></param>
|
||||
/// <param name="dateTime"></param>
|
||||
/// <returns>-1时即没找到</returns>
|
||||
private int SolarTermFunc(Expression<Func<int, int, bool>> func, out DateTime dateTime)
|
||||
{
|
||||
var baseDateAndTime = new DateTime(1900, 1, 6, 2, 5, 0); //#1/6/1900 2:05:00 AM#
|
||||
var year = _dateTime.Year;
|
||||
int[] solar = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
|
||||
var expressionType = func.Body.NodeType;
|
||||
if (expressionType != ExpressionType.LessThan && expressionType != ExpressionType.LessThanOrEqual &&
|
||||
expressionType != ExpressionType.GreaterThan && expressionType != ExpressionType.GreaterThanOrEqual &&
|
||||
expressionType != ExpressionType.Equal)
|
||||
{
|
||||
throw new NotSupportedException("不受支持的操作符");
|
||||
}
|
||||
|
||||
if (expressionType == ExpressionType.LessThan || expressionType == ExpressionType.LessThanOrEqual)
|
||||
{
|
||||
solar = solar.OrderByDescending(x => x).ToArray();
|
||||
}
|
||||
foreach (var item in solar)
|
||||
{
|
||||
var num = 525948.76 * (year - 1900) + _solarTermInfo[item - 1];
|
||||
var newDate = baseDateAndTime.AddMinutes(num); //按分钟计算
|
||||
if (func.Compile()(newDate.DayOfYear, _dateTime.DayOfYear))
|
||||
{
|
||||
dateTime = newDate;
|
||||
return item - 1;
|
||||
}
|
||||
}
|
||||
dateTime = _chineseDateTime.MinSupportedDateTime;
|
||||
return -1;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
1233
常用工具集/Utility/Core/ConvertHelper.cs
Normal file
55
常用工具集/Utility/Core/EnumHelper.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// 枚举类型操作公共类。
|
||||
/// </summary>
|
||||
public static class EnumHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取枚举所有成员名称。
|
||||
/// </summary>
|
||||
/// <typeparam name="T">枚举类型</typeparam>
|
||||
public static string[] GetNames<T>()
|
||||
{
|
||||
return Enum.GetNames(typeof(T));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测枚举是否包含指定成员。
|
||||
/// </summary>
|
||||
/// <typeparam name="T">枚举类型</typeparam>
|
||||
/// <param name="member">成员名或成员值</param>
|
||||
public static bool IsDefined(this Enum value)
|
||||
{
|
||||
Type type = value.GetType();
|
||||
return Enum.IsDefined(type, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回指定枚举类型的指定值的描述。
|
||||
/// </summary>
|
||||
/// <param name="t">枚举类型</param>
|
||||
/// <param name="v">枚举值</param>
|
||||
/// <returns></returns>
|
||||
public static string GetDescription(this Enum value)
|
||||
{
|
||||
try
|
||||
{
|
||||
Type type = value.GetType();
|
||||
FieldInfo field = type.GetField(value.ToString());
|
||||
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
|
||||
return (attributes.Length > 0) ? attributes[0].Description : string.Empty;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
257
常用工具集/Utility/Core/ExtDateTime.cs
Normal file
@@ -0,0 +1,257 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
public static class ExtDateTime
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒。格式:"yyyy-MM-dd"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToDateString(this DateTime dateTime)
|
||||
{
|
||||
return dateTime.ToString("yyyy-MM-dd");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒。格式:"yyyy-MM-dd"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToDateString(this DateTime? dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return ToDateString(dateTime.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带年月日,格式:"HH:mm:ss"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToTimeString(this DateTime dateTime)
|
||||
{
|
||||
return dateTime.ToString("HH:mm:ss");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带年月日,格式:"HH:mm:ss"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToTimeString(this DateTime? dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return ToTimeString(dateTime.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带毫秒,格式:"yyyy-MM-dd HH:mm:ss.fff"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToMillisecondString(this DateTime dateTime)
|
||||
{
|
||||
return dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带毫秒,格式:"yyyy-MM-dd HH:mm:ss.fff"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToMillisecondString(this DateTime? dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return ToMillisecondString(dateTime.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,不带时分秒,格式:"yyyy年MM月dd日"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
public static string ToChineseDateString(this DateTime dateTime)
|
||||
{
|
||||
return string.Format("{0}年{1}月{2}日", dateTime.Year, dateTime.Month, dateTime.Day);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带时分秒,格式:"yyyy年MM月dd日 HH时mm分"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
/// <param name="isRemoveSecond">是否移除秒</param>
|
||||
public static string ToChineseDateTimeString(this DateTime dateTime, bool isRemoveSecond = false)
|
||||
{
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.AppendFormat("{0}年{1}月{2}日", dateTime.Year, dateTime.Month, dateTime.Day);
|
||||
result.AppendFormat(" {0}时{1}分", dateTime.Hour, dateTime.Minute);
|
||||
|
||||
if (isRemoveSecond == false)
|
||||
{
|
||||
result.AppendFormat("{0}秒", dateTime.Second);
|
||||
}
|
||||
|
||||
return result.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取格式化字符串,带时分秒,格式:"yyyy年MM月dd日 HH时mm分"
|
||||
/// </summary>
|
||||
/// <param name="dateTime">日期</param>
|
||||
/// <param name="isRemoveSecond">是否移除秒</param>
|
||||
public static string ToChineseDateTimeString(this DateTime? dateTime, bool isRemoveSecond = false)
|
||||
{
|
||||
if (dateTime == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return ToChineseDateTimeString(dateTime.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回指定日期起始时间。
|
||||
/// </summary>
|
||||
/// <param name="dateTime"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime StartDateTime(this DateTime dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
{
|
||||
throw new ArgumentNullException();
|
||||
}
|
||||
|
||||
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
|
||||
}
|
||||
/// <summary>
|
||||
/// 返回指定日期结束时间。
|
||||
/// </summary>
|
||||
/// <param name="dateTime"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime EndDateTime(this DateTime dateTime)
|
||||
{
|
||||
if (dateTime == null)
|
||||
{
|
||||
throw new ArgumentNullException();
|
||||
}
|
||||
|
||||
return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 23, 59, 59);
|
||||
}
|
||||
|
||||
|
||||
#region 获取时间戳
|
||||
/// <summary>
|
||||
/// 获取时间戳
|
||||
/// </summary>
|
||||
public static string GetTimeStamp(DateTime dateTime)
|
||||
{
|
||||
DateTime dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
|
||||
return Convert.ToInt64(dateTime.Subtract(dtStart).TotalMilliseconds).ToString();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 根据时间戳获取时间
|
||||
/// <summary>
|
||||
/// 根据时间戳获取时间
|
||||
/// </summary>
|
||||
public static DateTime TimeStampToDateTime(string timeStamp)
|
||||
{
|
||||
DateTime dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
|
||||
return dtStart.AddMilliseconds(Convert.ToInt64(timeStamp));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本周开始时间
|
||||
/// <summary>
|
||||
/// 本周开始时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentWeekStart()
|
||||
{
|
||||
DateTime now = DateTime.Now;
|
||||
int day = Convert.ToInt32(now.DayOfWeek.ToString("d"));
|
||||
return now.AddDays(1 - day).Date;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本周结束时间
|
||||
/// <summary>
|
||||
/// 本周结束时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentWeekEnd()
|
||||
{
|
||||
return GetCurrentWeekStart().AddDays(7).AddSeconds(-1);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本月开始时间
|
||||
/// <summary>
|
||||
/// 本月开始时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentMonthStart()
|
||||
{
|
||||
DateTime now = DateTime.Now;
|
||||
return now.AddDays(1 - now.Day).Date;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本月结束时间
|
||||
/// <summary>
|
||||
/// 本月结束时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentMonthEnd()
|
||||
{
|
||||
return GetCurrentWeekStart().AddMonths(1).AddSeconds(-1);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本季度开始时间
|
||||
/// <summary>
|
||||
/// 本季度开始时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentQuarterStart()
|
||||
{
|
||||
DateTime now = DateTime.Now;
|
||||
return now.AddMonths(0 - (now.Month - 1) % 3).AddDays(1 - now.Day).Date;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本季度结束时间
|
||||
/// <summary>
|
||||
/// 本季度结束时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentQuarterthEnd()
|
||||
{
|
||||
return GetCurrentWeekStart().AddMonths(3).AddSeconds(-1);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本年开始时间
|
||||
/// <summary>
|
||||
/// 本年开始时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentYearStart()
|
||||
{
|
||||
return new DateTime(DateTime.Now.Year, 1, 1);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 本年结束时间
|
||||
/// <summary>
|
||||
/// 本年结束时间
|
||||
/// </summary>
|
||||
public static DateTime GetCurrentYearEnd()
|
||||
{
|
||||
return new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59);
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
143
常用工具集/Utility/Core/JsonHelper.cs
Normal file
@@ -0,0 +1,143 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
public static class JsonHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 对象序列化成JSON字符串。
|
||||
/// </summary>
|
||||
/// <param name="obj">序列化对象</param>
|
||||
/// <param name="ignoreProperties">设置需要忽略的属性</param>
|
||||
/// <returns></returns>
|
||||
public static string ToJson(this object obj)
|
||||
{
|
||||
if (obj == null)
|
||||
return string.Empty;
|
||||
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
|
||||
timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
|
||||
return JsonConvert.SerializeObject(obj, timeConverter);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON字符串序列化成对象。
|
||||
/// </summary>
|
||||
/// <typeparam name="T">对象类型</typeparam>
|
||||
/// <param name="json">JSON字符串</param>
|
||||
/// <returns></returns>
|
||||
public static T ToObject<T>(this string json)
|
||||
{
|
||||
//var setting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
|
||||
return json == null ? default(T) : JsonConvert.DeserializeObject<T>(json);//, setting);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// JSON字符串序列化成集合。
|
||||
/// </summary>
|
||||
/// <typeparam name="T">集合类型</typeparam>
|
||||
/// <param name="json">JSON字符串</param>
|
||||
/// <returns></returns>
|
||||
public static List<T> ToList<T>(this string json)
|
||||
{
|
||||
//var setting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
|
||||
return json == null ? null : JsonConvert.DeserializeObject<List<T>>(json);//, setting);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// JSON字符串序列化成DataTable。
|
||||
/// </summary>
|
||||
/// <param name="json">JSON字符串</param>
|
||||
/// <returns></returns>
|
||||
public static DataTable ToTable(this string json)
|
||||
{
|
||||
return json == null ? null : JsonConvert.DeserializeObject<DataTable>(json);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将JSON字符串反序列化成对象
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="baseEntity"></param>
|
||||
/// <param name="strJson"></param>
|
||||
/// <returns></returns>
|
||||
public static T Json2Obj<T>(T baseEntity, string strJson)
|
||||
{
|
||||
return JsonConvert.DeserializeAnonymousType(strJson, baseEntity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将对象转换层JSON字符串
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
public static string Obj2Json<T>(T data)
|
||||
{
|
||||
return JsonConvert.SerializeObject(data);
|
||||
}
|
||||
|
||||
|
||||
public static List<T> JsonToList<T>(string strJson)
|
||||
{
|
||||
T[] list = JsonConvert.DeserializeObject<T[]>(strJson);
|
||||
return list.ToList();
|
||||
}
|
||||
|
||||
public static T Json2Obj<T>(string strJson)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<T>(strJson);
|
||||
}
|
||||
|
||||
public static DataTable ToDataTable(this string json)
|
||||
{
|
||||
return json.ToTable();
|
||||
}
|
||||
|
||||
public static string RemoveComments(string code)
|
||||
{
|
||||
code = Regex.Replace(code, @"(?s)(?<=<!--).+?(?=-->)", "");
|
||||
code = Regex.Replace(code, @"/\*[\s\S]*?\*/", "", RegexOptions.IgnoreCase);
|
||||
code = Regex.Replace(code, @"^\s*//[\s\S]*?$", "", RegexOptions.Multiline);
|
||||
code = Regex.Replace(code, @"^\s*$\n", "", RegexOptions.Multiline);
|
||||
code = Regex.Replace(code, @"^\s*//[\s\S]*", "", RegexOptions.Multiline);
|
||||
return code;
|
||||
}
|
||||
|
||||
public static string FormatJson(this string json)
|
||||
{
|
||||
//格式化json字符串
|
||||
JsonSerializer serializer = new JsonSerializer();
|
||||
TextReader tr = new StringReader(json);
|
||||
JsonTextReader jtr = new JsonTextReader(tr);
|
||||
object obj = serializer.Deserialize(jtr);
|
||||
if (obj != null)
|
||||
{
|
||||
StringWriter textWriter = new StringWriter();
|
||||
JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
|
||||
{
|
||||
Formatting = Formatting.Indented,
|
||||
Indentation = 4,
|
||||
IndentChar = ' '
|
||||
};
|
||||
serializer.Serialize(jsonWriter, obj);
|
||||
return textWriter.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
return json;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
255
常用工具集/Utility/Core/LinqExtension.cs
Normal file
@@ -0,0 +1,255 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Text;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// LINQ扩展方法
|
||||
/// </summary>
|
||||
public static class LinqExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 与连接
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类型</typeparam>
|
||||
/// <param name="left">左条件</param>
|
||||
/// <param name="right">右条件</param>
|
||||
/// <returns>新表达式</returns>
|
||||
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
|
||||
{
|
||||
return CombineLambdas(left, right, ExpressionType.AndAlso);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 或连接
|
||||
/// </summary>
|
||||
/// <typeparam name="T">类型</typeparam>
|
||||
/// <param name="left">左条件</param>
|
||||
/// <param name="right">右条件</param>
|
||||
/// <returns>新表达式</returns>
|
||||
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
|
||||
{
|
||||
return CombineLambdas(left, right, ExpressionType.OrElse);
|
||||
}
|
||||
|
||||
private static Expression<Func<T, bool>> CombineLambdas<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right, ExpressionType expressionType)
|
||||
{
|
||||
var visitor = new SubstituteParameterVisitor
|
||||
{
|
||||
Sub =
|
||||
{
|
||||
[right.Parameters[0]] = left.Parameters[0]
|
||||
}
|
||||
};
|
||||
|
||||
Expression body = Expression.MakeBinary(expressionType, left.Body, visitor.Visit(right.Body));
|
||||
return Expression.Lambda<Func<T, bool>>(body, left.Parameters[0]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最大值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult MaxOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector) => source.Select(selector).OrderByDescending(_ => _).FirstOrDefault();
|
||||
|
||||
/// <summary>
|
||||
/// 取最大值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult MaxOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TResult defaultValue)
|
||||
{
|
||||
TResult result = source.Select(selector).OrderByDescending(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最大值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MaxOrDefault<TSource>(this IQueryable<TSource> source)
|
||||
{
|
||||
return source.OrderByDescending(_ => _).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最大值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MaxOrDefault<TSource>(this IQueryable<TSource> source, TSource defaultValue)
|
||||
{
|
||||
TSource result = source.OrderByDescending(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最大值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult MaxOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, TResult defaultValue)
|
||||
{
|
||||
TResult result = source.Select(selector).OrderByDescending(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最大值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource> source) => source.OrderByDescending(_ => _).FirstOrDefault();
|
||||
|
||||
/// <summary>
|
||||
/// 取最大值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
|
||||
{
|
||||
TSource result = source.OrderByDescending(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector) => source.Select(selector).OrderBy(_ => _).FirstOrDefault();
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult MinOrDefault<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector, TResult defaultValue)
|
||||
{
|
||||
TResult result = source.Select(selector).OrderBy(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source) => source.OrderBy(_ => _).FirstOrDefault();
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MinOrDefault<TSource>(this IQueryable<TSource> source, TSource defaultValue)
|
||||
{
|
||||
TSource result = source.OrderBy(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) => source.Select(selector).OrderBy(_ => _).FirstOrDefault();
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <typeparam name="TResult"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult MinOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, TResult defaultValue)
|
||||
{
|
||||
TResult result = source.Select(selector).OrderBy(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source) => source.OrderBy(_ => _).FirstOrDefault();
|
||||
|
||||
/// <summary>
|
||||
/// 取最小值
|
||||
/// </summary>
|
||||
/// <typeparam name="TSource"></typeparam>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TSource MinOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
|
||||
{
|
||||
TSource result = source.OrderBy(_ => _).FirstOrDefault();
|
||||
if (result != null)
|
||||
return result;
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
internal class SubstituteParameterVisitor : ExpressionVisitor
|
||||
{
|
||||
public Dictionary<Expression, Expression> Sub = new Dictionary<Expression, Expression>();
|
||||
|
||||
protected override Expression VisitParameter(ParameterExpression node)
|
||||
{
|
||||
return Sub.TryGetValue(node, out var newValue) ? newValue : node;
|
||||
}
|
||||
}
|
||||
}
|
||||
163
常用工具集/Utility/Core/RMB.cs
Normal file
@@ -0,0 +1,163 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
public static class RMB
|
||||
{/// <summary>
|
||||
/// 转换人民币大小金额
|
||||
/// </summary>
|
||||
/// <param name="num">金额</param>
|
||||
/// <returns>返回大写形式</returns>
|
||||
public static string ToRMB(this decimal num)
|
||||
{
|
||||
string str1 = "零壹贰叁肆伍陆柒捌玖"; //0-9所对应的汉字
|
||||
string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字
|
||||
string str3 = ""; //从原num值中取出的值
|
||||
string str4 = ""; //数字的字符串形式
|
||||
string str5 = ""; //人民币大写金额形式
|
||||
int i; //循环变量
|
||||
int j; //num的值乘以100的字符串长度
|
||||
string ch1 = ""; //数字的汉语读法
|
||||
string ch2 = ""; //数字位的汉字读法
|
||||
int nzero = 0; //用来计算连续的零值是几个
|
||||
int temp; //从原num值中取出的值
|
||||
|
||||
num = Math.Round(Math.Abs(num), 2); //将num取绝对值并四舍五入取2位小数
|
||||
str4 = ((long)(num * 100)).ToString(); //将num乘100并转换成字符串形式
|
||||
j = str4.Length; //找出最高位
|
||||
if (j > 15) { return "溢出"; }
|
||||
str2 = str2.Substring(15 - j); //取出对应位数的str2的值。如:200.55,j为5所以str2=佰拾元角分
|
||||
|
||||
//循环取出每一位需要转换的值
|
||||
for (i = 0; i < j; i++)
|
||||
{
|
||||
str3 = str4.Substring(i, 1); //取出需转换的某一位的值
|
||||
temp = Convert.ToInt32(str3); //转换为数字
|
||||
if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
|
||||
{
|
||||
//当所取位数不为元、万、亿、万亿上的数字时
|
||||
if (str3 == "0")
|
||||
{
|
||||
ch1 = "";
|
||||
ch2 = "";
|
||||
nzero = nzero + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (str3 != "0" && nzero != 0)
|
||||
{
|
||||
ch1 = "零" + str1.Substring(temp * 1, 1);
|
||||
ch2 = str2.Substring(i, 1);
|
||||
nzero = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
ch1 = str1.Substring(temp * 1, 1);
|
||||
ch2 = str2.Substring(i, 1);
|
||||
nzero = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//该位是万亿,亿,万,元位等关键位
|
||||
if (str3 != "0" && nzero != 0)
|
||||
{
|
||||
ch1 = "零" + str1.Substring(temp * 1, 1);
|
||||
ch2 = str2.Substring(i, 1);
|
||||
nzero = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (str3 != "0" && nzero == 0)
|
||||
{
|
||||
ch1 = str1.Substring(temp * 1, 1);
|
||||
ch2 = str2.Substring(i, 1);
|
||||
nzero = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (str3 == "0" && nzero >= 3)
|
||||
{
|
||||
ch1 = "";
|
||||
ch2 = "";
|
||||
nzero = nzero + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (j >= 11)
|
||||
{
|
||||
ch1 = "";
|
||||
nzero = nzero + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
ch1 = "";
|
||||
ch2 = str2.Substring(i, 1);
|
||||
nzero = nzero + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (i == (j - 11) || i == (j - 3))
|
||||
{
|
||||
//如果该位是亿位或元位,则必须写上
|
||||
ch2 = str2.Substring(i, 1);
|
||||
}
|
||||
str5 = str5 + ch1 + ch2;
|
||||
|
||||
if (i == j - 1 && str3 == "0")
|
||||
{
|
||||
//最后一位(分)为0时,加上“整”
|
||||
str5 = str5 + '整';
|
||||
}
|
||||
}
|
||||
if (num == 0)
|
||||
{
|
||||
str5 = "零元整";
|
||||
}
|
||||
return str5;
|
||||
}
|
||||
|
||||
public static string ToRMB(this int num)
|
||||
{
|
||||
return ToRMB(Convert.ToString(num));
|
||||
}
|
||||
|
||||
public static string ToRMB(this float num)
|
||||
{
|
||||
return ToRMB(Convert.ToString(num));
|
||||
}
|
||||
|
||||
public static string ToRMB(this double num)
|
||||
{
|
||||
return ToRMB(Convert.ToString(num));
|
||||
}
|
||||
|
||||
public static string ToRMB(this long num)
|
||||
{
|
||||
return ToRMB(Convert.ToString(num));
|
||||
}
|
||||
/// <summary>
|
||||
/// 一个重载,将字符串先转换成数字在调用CmycurD(decimal num)
|
||||
/// </summary>
|
||||
/// <param name="num">用户输入的金额,字符串形式未转成decimal</param>
|
||||
/// <returns></returns>
|
||||
public static string ToRMB(this string numstr)
|
||||
{
|
||||
try
|
||||
{
|
||||
decimal num = Convert.ToDecimal(numstr);
|
||||
return ToRMB(num);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "非数字形式!";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
61
常用工具集/Utility/Core/RandomHelper.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用Random类生成伪随机数
|
||||
/// </summary>
|
||||
public static class RandomHelper
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 生成一个指定范围的随机整数,该随机数范围包括最小值,但不包括最大值
|
||||
/// </summary>
|
||||
/// <param name="minNum">最小值</param>
|
||||
/// <param name="maxNum">最大值</param>
|
||||
public static int GetRandomInt(int minNum, int maxNum)
|
||||
{
|
||||
return new Random().Next(minNum, maxNum);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成一个0.0到1.0的随机小数
|
||||
/// </summary>
|
||||
public static double GetRandomDouble()
|
||||
{
|
||||
return new Random().NextDouble();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对一个数组进行随机排序
|
||||
/// </summary>
|
||||
/// <typeparam name="T">数组的类型</typeparam>
|
||||
/// <param name="arr">需要随机排序的数组</param>
|
||||
public static void GetRandomArray<T>(T[] arr)
|
||||
{
|
||||
//对数组进行随机排序的算法:随机选择两个位置,将两个位置上的值交换
|
||||
|
||||
//交换的次数,这里使用数组的长度作为交换次数
|
||||
int count = arr.Length;
|
||||
|
||||
//开始交换
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
//生成两个随机数位置
|
||||
int targetIndex1 = GetRandomInt(0, arr.Length);
|
||||
int targetIndex2 = GetRandomInt(0, arr.Length);
|
||||
|
||||
//定义临时变量
|
||||
T temp;
|
||||
|
||||
//交换两个随机数位置的值
|
||||
temp = arr[targetIndex1];
|
||||
arr[targetIndex1] = arr[targetIndex2];
|
||||
arr[targetIndex2] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
35
常用工具集/Utility/Core/RegexHelper.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// 操作正则表达式的公共类
|
||||
/// </summary>
|
||||
public class RegexHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 验证输入字符串是否与模式字符串匹配,匹配返回true
|
||||
/// </summary>
|
||||
/// <param name="input">输入字符串</param>
|
||||
/// <param name="pattern">模式字符串</param>
|
||||
public static bool IsMatch(string input, string pattern)
|
||||
{
|
||||
return IsMatch(input, pattern, RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证输入字符串是否与模式字符串匹配,匹配返回true
|
||||
/// </summary>
|
||||
/// <param name="input">输入的字符串</param>
|
||||
/// <param name="pattern">模式字符串</param>
|
||||
/// <param name="options">筛选条件</param>
|
||||
public static bool IsMatch(string input, string pattern, RegexOptions options)
|
||||
{
|
||||
return Regex.IsMatch(input, pattern, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
277
常用工具集/Utility/Core/RegisterHelper.cs
Normal file
@@ -0,0 +1,277 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.Win32;
|
||||
using System.Reflection;
|
||||
|
||||
namespace MES.Utility.Core
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 注册表辅助类
|
||||
/// </summary>
|
||||
public class RegisterHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 默认注册表基项
|
||||
/// </summary>
|
||||
private string baseKey = "Software";
|
||||
|
||||
#region 构造函数
|
||||
/// <summary>
|
||||
/// 构造函数
|
||||
/// </summary>
|
||||
/// <param name="baseKey">基项的名称</param>
|
||||
public RegisterHelper()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数
|
||||
/// </summary>
|
||||
/// <param name="baseKey">基项的名称</param>
|
||||
public RegisterHelper(string baseKey)
|
||||
{
|
||||
this.baseKey = baseKey;
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 公共方法
|
||||
|
||||
/// <summary>
|
||||
/// 写入注册表,如果指定项已经存在,则修改指定项的值
|
||||
/// </summary>
|
||||
/// <param name="keytype">注册表基项枚举</param>
|
||||
/// <param name="key">注册表项,不包括基项</param>
|
||||
/// <param name="name">值名称</param>
|
||||
/// <param name="values">值</param>
|
||||
public void SetValue(KeyType keytype, string key, string name, string values)
|
||||
{
|
||||
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
|
||||
RegistryKey software = rk.OpenSubKey(baseKey, true);
|
||||
RegistryKey rkt = software.CreateSubKey(key);
|
||||
if (rkt != null)
|
||||
{
|
||||
rkt.SetValue(name, values);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 读取注册表
|
||||
/// </summary>
|
||||
/// <param name="keytype">注册表基项枚举</param>
|
||||
/// <param name="key">注册表项,不包括基项</param>
|
||||
/// <param name="name">值名称</param>
|
||||
/// <returns>返回字符串</returns>
|
||||
public string GetValue(KeyType keytype, string key, string name)
|
||||
{
|
||||
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
|
||||
RegistryKey software = rk.OpenSubKey(baseKey, true);
|
||||
RegistryKey rkt = software.OpenSubKey(key);
|
||||
|
||||
if (rkt != null)
|
||||
{
|
||||
return rkt.GetValue(name).ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 删除注册表中的值
|
||||
/// </summary>
|
||||
/// <param name="keytype">注册表基项枚举</param>
|
||||
/// <param name="key">注册表项名称,不包括基项</param>
|
||||
/// <param name="name">值名称</param>
|
||||
public void DeleteValue(KeyType keytype, string key, string name)
|
||||
{
|
||||
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
|
||||
RegistryKey software = rk.OpenSubKey(baseKey, true);
|
||||
RegistryKey rkt = software.OpenSubKey(key, true);
|
||||
|
||||
if (rkt != null)
|
||||
{
|
||||
object value = rkt.GetValue(name);
|
||||
if (value != null)
|
||||
{
|
||||
rkt.DeleteValue(name, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 删除注册表中的指定项
|
||||
/// </summary>
|
||||
/// <param name="keytype">注册表基项枚举</param>
|
||||
/// <param name="key">注册表中的项,不包括基项</param>
|
||||
/// <returns>返回布尔值,指定操作是否成功</returns>
|
||||
public void DeleteSubKey(KeyType keytype, string key)
|
||||
{
|
||||
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
|
||||
RegistryKey software = rk.OpenSubKey(baseKey, true);
|
||||
if (software != null)
|
||||
{
|
||||
software.DeleteSubKeyTree(key);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 判断指定项是否存在
|
||||
/// </summary>
|
||||
/// <param name="keytype">基项枚举</param>
|
||||
/// <param name="key">指定项字符串</param>
|
||||
/// <returns>返回布尔值,说明指定项是否存在</returns>
|
||||
public bool IsExist(KeyType keytype, string key)
|
||||
{
|
||||
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
|
||||
RegistryKey software = rk.OpenSubKey(baseKey);
|
||||
RegistryKey rkt = software.OpenSubKey(key);
|
||||
if (rkt != null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 检索指定项关联的所有值
|
||||
/// </summary>
|
||||
/// <param name="keytype">基项枚举</param>
|
||||
/// <param name="key">指定项字符串</param>
|
||||
/// <returns>返回指定项关联的所有值的字符串数组</returns>
|
||||
public string[] GetValues(KeyType keytype, string key)
|
||||
{
|
||||
RegistryKey rk = (RegistryKey)GetRegistryKey(keytype);
|
||||
RegistryKey software = rk.OpenSubKey(baseKey, true);
|
||||
RegistryKey rkt = software.OpenSubKey(key);
|
||||
string[] names = rkt.GetValueNames();
|
||||
|
||||
if (names.Length == 0)
|
||||
{
|
||||
return names;
|
||||
}
|
||||
else
|
||||
{
|
||||
string[] values = new string[names.Length];
|
||||
|
||||
int i = 0;
|
||||
|
||||
foreach (string name in names)
|
||||
{
|
||||
values[i] = rkt.GetValue(name).ToString();
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将对象所有属性写入指定注册表中
|
||||
/// </summary>
|
||||
/// <param name="keytype">注册表基项枚举</param>
|
||||
/// <param name="key">注册表项,不包括基项</param>
|
||||
/// <param name="obj">传入的对象</param>
|
||||
public void SetObjectValue(KeyType keyType, string key, Object obj)
|
||||
{
|
||||
if (obj != null)
|
||||
{
|
||||
Type t = obj.GetType();
|
||||
|
||||
string name;
|
||||
object value;
|
||||
foreach (var p in t.GetProperties())
|
||||
{
|
||||
if (p != null)
|
||||
{
|
||||
name = p.Name;
|
||||
value = p.GetValue(obj, null);
|
||||
this.SetValue(keyType, key, name, value.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 私有方法
|
||||
|
||||
/// <summary>
|
||||
/// 返回RegistryKey对象
|
||||
/// </summary>
|
||||
/// <param name="keyType">注册表基项枚举</param>
|
||||
/// <returns></returns>
|
||||
private object GetRegistryKey(KeyType keyType)
|
||||
{
|
||||
RegistryKey rk = null;
|
||||
|
||||
switch (keyType)
|
||||
{
|
||||
case KeyType.HKEY_CLASS_ROOT:
|
||||
rk = Registry.ClassesRoot;
|
||||
break;
|
||||
case KeyType.HKEY_CURRENT_USER:
|
||||
rk = Registry.CurrentUser;
|
||||
break;
|
||||
case KeyType.HKEY_LOCAL_MACHINE:
|
||||
rk = Registry.LocalMachine;
|
||||
break;
|
||||
case KeyType.HKEY_USERS:
|
||||
rk = Registry.Users;
|
||||
break;
|
||||
case KeyType.HKEY_CURRENT_CONFIG:
|
||||
rk = Registry.CurrentConfig;
|
||||
break;
|
||||
}
|
||||
|
||||
return rk;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 枚举
|
||||
/// <summary>
|
||||
/// 注册表基项枚举
|
||||
/// </summary>
|
||||
public enum KeyType : int
|
||||
{
|
||||
/// <summary>
|
||||
/// 注册表基项 HKEY_CLASSES_ROOT
|
||||
/// </summary>
|
||||
HKEY_CLASS_ROOT,
|
||||
/// <summary>
|
||||
/// 注册表基项 HKEY_CURRENT_USER
|
||||
/// </summary>
|
||||
HKEY_CURRENT_USER,
|
||||
/// <summary>
|
||||
/// 注册表基项 HKEY_LOCAL_MACHINE
|
||||
/// </summary>
|
||||
HKEY_LOCAL_MACHINE,
|
||||
/// <summary>
|
||||
/// 注册表基项 HKEY_USERS
|
||||
/// </summary>
|
||||
HKEY_USERS,
|
||||
/// <summary>
|
||||
/// 注册表基项 HKEY_CURRENT_CONFIG
|
||||
/// </summary>
|
||||
HKEY_CURRENT_CONFIG
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||