Giter Site home page Giter Site logo

ldqk / masuit.tools Goto Github PK

View Code? Open in Web Editor NEW
5.1K 142.0 1.2K 9.97 MB

全龄段友好的C#万能工具库,码数吐司库,包含一些常用的操作类,大都是静态类,加密解密,反射操作,权重随机筛选算法,分布式短id,表达式树,linq扩展,文件压缩,多线程下载,硬件信息,字符串扩展方法,日期时间扩展操作,**农历,大文件拷贝,图像裁剪,验证码,断点续传,集合扩展、Excel导出等常用封装。诸多功能集一身,代码量不到2MB!

Home Page: https://www.masuit.tools/

License: MIT License

C# 100.00%
lambda reflection datetime expression linq multithreading encryption excel-export excel net5

masuit.tools's Introduction

懒得勤快 懒得勤快 懒得勤快 懒得勤快 懒得勤快

懒得勤快's github stats 主要使用语言 profile

个人简介

  • 懒得勤快,男,95后,程序猿,高级CV工程师,资深哲♂学家,SNP大一统理论研究爱好者,新日暮里娼片公司继承人,懒得勤快博客站长,微软、阿里巴巴等集团投资人,京东、淘宝等电商平台战略合作伙伴。
  • 现任职于: 尻♂立新日暮里♂大学·哲♂学教授;新日暮里♂娼片公司·总茎♂理兼CEO;幻想乡♂影视传媒·传播dark♂使;广door纳斯♂dark克公司·平家♂boy;新日暮里驻华大shit♂馆·馆长
  • 南山下,码农一枚。酷爱编程,乐于分享。
  • 09年开始接触编程,致力于更好的分享技术,分享人生。
  • 程序老鸟,初心不改!依然喜欢写代码到深夜,最喜欢深夜代码伴随着的键盘声。
  • 善于写别人看不懂的代码和上万行的屎山函数,以彰显自己不可替代的地位。(不信你们可以看看我的开源项目)
  • 喜欢折腾和搞机,追求新鲜的硬件数码设备,也欢迎小伙伴们一起讨论搞机经验,一起来tree new bee;
  • 2005年就读于美国联邦总局学院,2006年美国时代周刊年度年度人物,2008年感动中国组委会特别大奖,2010年被奥巴马请回到海豹突击队,2011年参加了美国总统选举二次落选,2012年被提名为世界最具影响力人物,2014年放弃一生辉煌隐退在互联网当码农;
  • 作为Microsoft、Google、Intel、NVIDIA、Qualcomm、中国电信、阿里巴巴集团、百度、腾讯、京东、哔哩哔哩、招商银行、台湾华硕股份、深圳万普拉斯科技、中国证监局、国家电网、中国铁路局等数十家国内外企业的投资人之一,并且保持着长期稳定的贸易与投资关系,每年助力企业产生数百亿的交易额的同时,为人低调;
  • 同时也是一位B站资深哲♂学家,探索未知领域😏。

Star趋势

Masuit.Tools
Masuit.MyBlogs Masuit.LuceneEFCore.SearchEngine

个人宗旨

互联网分享精神!勤于发现,乐于分享!山外青山楼外楼,比上不足比下有余;规则是用来打破的,王道是用来颠覆的!

小广告

专业维修核潜艇,原子弹翻新/抛光/打蜡,大修核反应堆,拆洗导弹发动机更换机油,回收二手航母、火箭,战斗机手动改自动,航天飞机保养换三滤,高空作业擦洗卫星表面除尘,飞碟外太空年检,各型号导弹加装迎宾踏板。批发战斗机/轰炸机/歼10,F22,F35/东风全系列巡航导弹、各类核弹头、1nm EUV光刻机。出售各类火车内外胎,飞机转弯灯,量大从优!有发票!全面接受预定歼20,送飞机后视镜,挡风玻璃贴膜,还有惊喜小礼品钥匙扣,打火机等;承接喜马拉雅山装电梯、太平洋加盖工程、月球装修等大型工程项目。另,新到一批纯天然野生散养奥特曼和葫芦娃,欢迎咨询订购…… !
QQ截图20211025101612_看图王

同狌交伖➕Q3️⃣4️㈣4️⃣⑺6️⃣4️⃣陆1️7️⃣✅🔞

default.mp4

masuit.tools's People

Contributors

chenjingchun avatar dependabot[bot] avatar gaven-f avatar gtxck avatar hjkl950217 avatar jiffei avatar jtone123 avatar ldqk avatar murdering avatar qjesus avatar wujianfeng17 avatar yzpopulation avatar zhaoyis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

masuit.tools's Issues

一些建议

多线程下载建议添加可配置参数
如 修改UA,添加Cookie,添加Headers
添加CPU序列号,硬盘序列号

将nuget包拆分

请将现在的单个nuget包拆分成多个nuget包。
Masuit.EF;Masuit.File

MultiThreadDownloader 出现 System.IO.IOException 和 System.InvalidOperationException 异常

使用的版本:nuget 2.2.7.3
.net框架: .net framework 3.7

MultiThreadDownloader 这个类抛出异常

System.InvalidOperationException: 集合已修改;可能无法执行枚举操作。
   在 System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   在 System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   在 System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
   在 System.Linq.Enumerable.Sum(IEnumerable`1 source)
   在 Masuit.Tools.Net.MultiThreadDownloader.get_TotalBytesReceived() 位置 D:\MyCode\Masuit.Tools\Masuit.Tools\Net\MultiThreadDownloader.cs:行号 64
   在 Masuit.Tools.Net.MultiThreadDownloader.UpdateProgress() 位置 D:\MyCode\Masuit.Tools\Masuit.Tools\Net\MultiThreadDownloader.cs:行号 198
   在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   在 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   在 System.Threading.ThreadPoolWorkQueue.Dispatch()

出现这个异常后文件能正常下载完成,异常出现在文件合并的时候


System.IO.IOException
  HResult=0x80070020
  Message=文件“C:\Users\cnwan\AppData\Local\Temp\2d54b17c-61f6-45c2-9357-0c9100f26fa2”正由另一进程使用,因此该进程无法访问此文件。
  Source=mscorlib
  StackTrace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalDelete(String path, Boolean checkHost)
   at Masuit.Tools.Net.MultiThreadDownloader.MergeParts()
   at Masuit.Tools.Net.MultiThreadDownloader.temp_DownloadPartCompleted(Object sender, EventArgs e)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

这个异常出现在下载过程之中,文件不能下载完成

[BUG]SevenZipCompressor解压7z压缩包报异常

bug描述
SevenZipCompressor解压7z压缩包报异常,压缩包是通过7z官方安装的图形化工具压缩的

image

是哪个函数出现了bug
SevenZipCompressor.Decompress

异常堆栈信息
image

函数入参
SevenZipCompressor.Decompress(@"E:\Download\11.7z", @"E:\Download");

期望的结果或输出
正常解压和压缩7z压缩包

使用环境:

  • OS: [WIN10]
  • Version [2.4.5.5]
  • .NET Runtime [4.8]

您的一些其他的想法

Cannot create Archives of type: SevenZip

.Net Core 3.1项目
操作步骤
1、Startup中ConfigureServices添加服务
//注入7z和断点续传 services.AddSevenZipCompressor().AddResumeFileResult();
2、构造函数注入
private readonly ISevenZipCompressor _sevenZipCompressor; public ScRecordsScreeningRepository(IWebHostEnvironment env, ISevenZipCompressor sevenZipCompressor) : base(dbFactory.Db(Constants.SystemDbKey), user) { _env = env; _sevenZipCompressor = sevenZipCompressor; }
3、使用7z
MemoryStream ms = _sevenZipCompressor.ZipStream(new List<string>() { @"D:\1.txt", "http://ww3.sinaimg.cn/large/87c01ec7gy1fsq6rywto2j20je0d3td0.jpg", });
结果:在使用时报'System.NotSupportedException:“Cannot create Archives of type: SevenZip”'

请求添加新功能:希望可以添加自定义列头名称

目前列头好像不支持特殊字符,包括一些括号之类的,因为是select new 出来的,只能符合c#变量命名规范,希望添加自定义列头。有个不成熟的想法,就是传参的时候再传个dictionary,里面的key作为select出来的变量,value对应实际要显示的列头名称。

支持netstandard 2.0

能否去除System.Drawing引用及相关图片处理库,然后支持netstandard2.0?

调整结构

  1. 抽取公共代码,抽取成一个“Abstractions”
  2. 配置github action

7z解压不了

SevenZipCompressor.Decompress(@"D:\Download\test.7z", @"D:\Download\");
Unhandled exception. System.InvalidOperationException: Cannot determine compressed stream type.  Supported Reader Formats: Zip, GZip, BZip2, Tar, Rar, LZip, XZ
   at SharpCompress.Readers.ReaderFactory.Open(Stream stream, ReaderOptions options)
   at Masuit.Tools.Files.SevenZipCompressor.Decompress(String compressedFile, String dir, Boolean ignoreEmptyDir) in \ldqk\Masuit.Tools\Masuit.Tools.Abstractions\Files\SevenZipCompressor.cs:line 122

[BUG]下载超过8G的文件没有反应

温馨提示:提交后请保证回复及时,若长时间未回复的issue,将在超过30天以后作关闭处理!

bug描述
下载超过8G的文件没有反应,未找到bug原因
使用环境:

  • OS: [e.g. iOS]
  • Version [e.g. 22]
  • .NET Runtime [e.g. 6.0]

您的一些其他的想法

socket相关的代码要引用哪个命名空间?

var tcpClient = new TcpClient(AddressFamily.InterNetwork);
Socket socket = tcpClient.ConnectSocket(IPAddress.Any,5000);
socket.SendFile("D:\test\1.txt",false,i =>
{
Console.WriteLine("已发送"+i+"%");
});

能否支持List分割扩展

能否支持IEnumerable分割扩展?
1.如有个List 有 200000 元素 要平均分成 5个list
2.如有个List 有 200000 元素 分成每个List 1000个(主要用于数据库录入数据时,一次太多影响拼接性能,需要分割)

建议代码如下,可能抄写的不是很好,也是百度的
1.
splitlist(this list src,int nsize){
for (int i=0;i<src.count;i+=nsize){
yield return src.getrange(i,math.min(nsize,src.count-i));
}
}
2.
chucklist (this list src,int nsize){
int count=src.count/nsize;
if (src.count % nsize !=0){
count++;
}
for (int i=0;i<nsize;i++){
if (i==nsize-1){
yield return src.getrange(icount,src.count-icount);
}else{
yield return src.getrange(i*count,count);
}
}
}

.net stardand2.0支持

没什么必要直接上到.net stardand 2.1吧?2.1直接就把.net framework抛弃掉了啊。
既然.net framework版本的已经到了4.6.1,为什么不直接做成.net stardand 2.0支持呢?这样更方便一点把?

在Blog.core框架中通过nuget安装Masuit.Tool后,启动项目在UseEndpoint时候出现以下错误

DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor(Microsoft.AspNetCore.Mvc.Infrastructure.IActionDescriptorCollectionProvider, Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory)' on type 'ControllerActionEndpointDataSource'.

ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load file or assembly 'Masuit.Tools.Abstractions, Version=2.3.1.5, Culture=neutral, PublicKeyToken=null'. 系统找不到指定的文件。
Could not load file or assembly 'Masuit.Tools.Abstractions, Version=2.3.1.5, Culture=neutral, PublicKeyToken=null'. 系统找不到指定的文件。
Could not load file or assembly 'Masuit.Tools.Abstractions, Version=2.3.1.5, Culture=neutral, PublicKeyToken=null'. 系统找不到指定的文件。
Could not load file or assembly 'Masuit.Tools.Abstractions, Version=2.3.1.5, Culture=neutral, PublicKeyToken=null'. 系统找不到指定的文件。

请问这种应该如何定位 谢谢

获取用户本机IP地址的方法

Masuit.Tools/Masuit.Tools.Core/Win32/Windows.cs
正常的一台机器可能会有多个IP地址,应该返回 string[] 类型吧?
以下写法是否更合适?

public static string[] GetLocalUsedIP()
{

		try
		{
			var ipList = new List<string>();
			var ipAddress = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
			foreach(var ip in ipAddress)
			{
				if(ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
				{
					ipList.Add(ip.ToString());
				}
			}
			return ipList.ToArray();
		}
		catch
		{
			return null;
		}
	}

配置项可以添加更多默认行为

比如AES或者MD5的默认密钥可以在appsetting中设置之类,MD5默认密钥好像是个静态属性,但是AES的默认密钥好像是readyonly的,如果无法设置,不得每次都带上密钥么,或者在加密之上在封装一个带密钥的加解密方法?

依赖ASP.NET Core Mvc而无法被Blazor直接或间接引用

当Blazor项目安装包Masuit.Tools或其引用的项目(比如某些共享的模型)安装了Masuit.Tools时,编译器会报错:

严重性	代码	说明	项目	文件	行	禁止显示状态
错误	CS0234	命名空间“Microsoft.AspNetCore.Mvc.ApplicationParts”中不存在类型或命名空间名“ApplicationPartAttribute”(是否缺少程序集引用?)	DotBlog.Blazor	xxxx\obj\Debug\net5.0\xxxx.MvcApplicationPartsAssemblyInfo.cs	14	活动

(这个报错挺迷惑的,因为它报错的文件是MSbuild自动生成的)
原因是Blazor不支持使用ASP.NET Core Mvc的二进制库相关issue链接,而Masuit.Tools依赖中有ASP.NET Core Mvc。
我不知道能否不依赖于ASP.NET Core Mvc。为了防止后来者踩坑就发个issue
(说实话Blazor不能用Masuit.Tools挺难受的,毕竟很难找到和这个媲美的工具库)

[BUG] DistinctBy去重存在问题

IEnumerable<int> arr = new List<int>() { 1, 2, 3 };

arr=arr.DistinctByEx(it => it);
arr.Count();
// 迭代无法获取到值
foreach (var i in arr)
{
    Console.Out.WriteLine("i={0}", i);
}
public static class Test
{
    public static IEnumerable<TSource> DistinctByEx<TSource, TKey>(
        this IEnumerable<TSource> source,
        Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> hash = new HashSet<TKey>();
        return source.Where<TSource>((Func<TSource, bool>) (p => hash.Add(keySelector(p))));
    }

}

使用了Count之后无法遍历集合,调试发现在Count内部调用了where的条件判断:

image

导致foreach遍历时迭代器再次判断where条件时HashSet内部已经有值

image

建议替换成System.Linq内的官方写法,实测没有问题

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
{
    if (source is null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
    }
    if (keySelector is null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keySelector);
    }

    return DistinctByIterator(source, keySelector, comparer);
}

private static IEnumerable<TSource> DistinctByIterator<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
{
    using IEnumerator<TSource> enumerator = source.GetEnumerator();

    if (enumerator.MoveNext())
    {
        var set = new HashSet<TKey>(DefaultInternalSetCapacity, comparer);
        do
        {
            TSource element = enumerator.Current;
            if (set.Add(keySelector(element)))
            {
                yield return element;
            }
        }
        while (enumerator.MoveNext());
    }
}

希望可以升级到最新版本

执行 Install-Package Masuit.Tools.Core
返回 ` Install-Package : NU1605: 检测到包降级: Microsoft.Extensions.DependencyInjection 从 3.1.2 降级到 3.1.0。直接从项目引用包以选择不同版本。
Coldairarrow.Api -> Masuit.Tools.Core 2.2.8.4 -> Microsoft.EntityFrameworkCore 3.1.2 -> Microsoft.Extensions.DependencyInjection (>= 3.1.2)
Coldairarrow.Api -> Microsoft.Extensions.DependencyInjection (>= 3.1.0)
所在位置 行:1 字符: 1

  • Install-Package Masuit.Tools.Core
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    
    

Install-Package : NU1605: 检测到包降级: Microsoft.Extensions.DependencyInjection 从 3.1.2 降级到 3.1.0。直接从项目引用包以选择不同版本。
Coldairarrow.Api -> Masuit.Tools.Core 2.2.8.4 -> Microsoft.Extensions.Http 3.1.2 -> Microsoft.Extensions.Logging 3.1.2 -> Microsoft.Extensions.DependencyInjection (>= 3.1.2)
Coldairarrow.Api -> Microsoft.Extensions.DependencyInjection (>= 3.1.0)
所在位置 行:1 字符: 1

  • Install-Package Masuit.Tools.Core
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    
    

Install-Package : 程序包还原失败。正在回滚“05.Coldairarrow.Api”的程序包更改。
所在位置 行:1 字符: 1

  • Install-Package Masuit.Tools.Core
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    

`

系统环境 netcore 3.1.1

请问

请问一下师傅,我想个人做个开源项目可以使用吗。。

[BUG]文件下载功能,下载超过2g文件报错

温馨提示:提交后请保证回复及时,若长时间未回复的issue,将在超过30天以后作关闭处理!

bug描述
[BUG]文件下载功能,下载超过2g文件报错

解决方法
Masuit.Tools.Abstractions\Net\PartialDownloader.cs
给From 和 TO 的 Int 改成 Long

Linux平台下RSA加密出现问题

Windows平台下没有问题
服务版本:ASP.Net Core2.1
Masuit.Tools版本

Masuit.Tools.NET 2.2.9.1

windows平台下正常
Linux环境下:
异常信息:
An unhandled exception has occurred while executing the request.
System.PlatformNotSupportedException: 'CspParameters' requires Windows Cryptographic API (CAPI), which is not available on this platform.
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)
at Masuit.Tools.Security.RsaPem.GetRSA()
at Masuit.Tools.Security.RSA..ctor(String key)

图片类会自动释放

使用类似bitmap.ResizeImage的方法时,获取到的bitmap因为在方法内使用了using,会得到一个不正确的bitmap。
无法进行后续处理

StrictNext不安全

函数原型

  /// <summary>
  /// 生成真正的随机数
  /// </summary>
  /// <param name="r"></param>
  /// <param name="seed"></param>
  /// <returns></returns>
  public static int StrictNext(this Random r, int seed = int.MaxValue)
  {
      return new Random((int)Stopwatch.GetTimestamp()).Next(seed);
  }

错误原因

Random((int)Stopwatch.GetTimestamp()).Next(seed)依赖于生成随机数的时间,也就是(int)Stopwatch.GetTimestamp(),如果我知道你生成的时间,那么我就可以猜测你产生的随机数。

因此这个方法是不安全的,不应该用于加密密钥和保护敏感信息的盐。

如果,您希望产生一个不可预测的安全随机数,应该使用RNGCryptoServiceProvider。system.Security.Cryptography.RNGCryptoServiceProvider的类,它采用系统当前的硬件信息、进程信息、线程信息、系统启动时间和当前精确时间作为填充因子,通过更好的算法生成高质量的随机数

https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.rngcryptoserviceprovider?view=net-5.0#code-try-3

//The following sample uses the Cryptography class to simulate the roll of a dice.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

class RNGCSP
{
    private static RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
    // Main method.
    public static void Main()
    {
        const int totalRolls = 25000;
        int[] results = new int[6];

        // Roll the dice 25000 times and display
        // the results to the console.
        for (int x = 0; x < totalRolls; x++)
        {
            byte roll = RollDice((byte)results.Length);
            results[roll - 1]++;
        }
        for (int i = 0; i < results.Length; ++i)
        {
            Console.WriteLine("{0}: {1} ({2:p1})", i + 1, results[i], (double)results[i] / (double)totalRolls);
        }
        rngCsp.Dispose();
    }

    // This method simulates a roll of the dice. The input parameter is the
    // number of sides of the dice.

    public static byte RollDice(byte numberSides)
    {
        if (numberSides <= 0)
            throw new ArgumentOutOfRangeException("numberSides");

        // Create a byte array to hold the random value.
        byte[] randomNumber = new byte[1];
        do
        {
            // Fill the array with a random value.
            rngCsp.GetBytes(randomNumber);
        }
        while (!IsFairRoll(randomNumber[0], numberSides));
        // Return the random number mod the number
        // of sides.  The possible values are zero-
        // based, so we add one.
        return (byte)((randomNumber[0] % numberSides) + 1);
    }

    private static bool IsFairRoll(byte roll, byte numSides)
    {
        // There are MaxValue / numSides full sets of numbers that can come up
        // in a single byte.  For instance, if we have a 6 sided die, there are
        // 42 full sets of 1-6 that come up.  The 43rd set is incomplete.
        int fullSetsOfValues = Byte.MaxValue / numSides;

        // If the roll is within this range of fair values, then we let it continue.
        // In the 6 sided die case, a roll between 0 and 251 is allowed.  (We use
        // < rather than <= since the = portion allows through an extra 0 value).
        // 252 through 255 would provide an extra 0, 1, 2, 3 so they are not fair
        // to use.
        return roll < numSides * fullSetsOfValues;
    }
}

另外,AES和其他加密算法的key尽量使用byte[] 有助于提高安全性

[建议]移除方法的建议

为了保证兼容性,建议:
如果你打算移除一个方法,建议标记这个方法为废弃,而不删除。
同时,在代码里或更新记录里描述替代方法或描述为什么
然后在以后几个的版本中再完全移除。

MultiThreadDownloader类抛出System.IO.IOException

在此前的issue中已有相同问题,但我发现改问题仍未得到妥善的解决。

我不确定是否是我的代码问题引起异常,因此我创建了一个测试工程以复现问题
环境:.Net Framework 4.6.1
Nuget版本:Masuit.Tools.Net 2.2.8.9
代码如下:

static void Main(string[] args)
        {
            var mtd1 = new MultiThreadDownloader("url",  Environment.CurrentDirectory+"\\test1.png", 1);
            mtd1.Start();
            Console.ReadLine();

            var mtd2 = new MultiThreadDownloader("url", Environment.CurrentDirectory + "\\test2.png", 1);
            mtd2.Start();
            Console.ReadLine();
        }

以下是异常信息:
System.IO.IOException
HResult=0x80070020
Message=文件“C:\Users\23877\AppData\Local\Temp\c5ef965e-b056-4a54-9090-6af3b596eefc”正由另一进程使用,因此该进程无法访问此文件。
Source=mscorlib
StackTrace:
在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
在 Masuit.Tools.Net.MultiThreadDownloader.MergeParts()
在 Masuit.Tools.Net.MultiThreadDownloader.temp_DownloadPartCompleted(Object sender, EventArgs e)
在 Masuit.Tools.Net.PartialDownloader.b__60_0(Object state)
在 System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
在 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
在 System.Threading.ThreadPoolWorkQueue.Dispatch()
在 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

请求添加新功能:DateTime to string

温馨提示:提交后请保证回复及时,若长时间未回复的issue,将在超过30天以后作关闭处理!

请详细描述一下你想要的功能,实现什么效果?

导出Excel,DateTime类型是否能直接转成时间字符串

image

获取真实文件类型报错

bug描述
获取真实文件类型,报错:

Unable to load one or more of the requested types.
Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. 系统找不到指定的文件。
Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. 系统找不到指定的文件。
Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. 系统找不到指定的文件。
Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. 系统找不到指定的文件。

是哪个函数出现了bug

var filepath = @"D:\git\ConsoleApp1\ConsoleApp1\ConsoleApp1\file\f\新建 Microsoft Word 文档.docx";

// 报错
 var detector = new FileInfo(filepath).DetectFiletype();

异常堆栈信息

   在 Masuit.Tools.Files.FileDetector.FileSignatureDetector.DetectFiletype(FileInfo file)
   在 ConsoleApp1.Program.<Test>d__6.MoveNext() 在 D:\git\ConsoleApp1\ConsoleApp1\ConsoleApp1\Program.cs 中: 第 640 行
   在 ConsoleApp1.Program.<Main>d__5.MoveNext() 在 D:\git\ConsoleApp1\ConsoleApp1\ConsoleApp1\Program.cs 中: 第 630 行

函数入参

期望的结果或输出
获取真实文件类型

使用环境:

  • OS: Windows10 专业版 19043.1889
  • Version VS2022
  • .NET Runtime 6.0

您的一些其他的想法

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.