.net总结

.net总结

目录

.net总结

配置

IIS

程序设计

程序

Parallel并行执行任务,最好配合线程安全List

线程安全的list

Winform跨线程更新UI界面

读取Json配置文件

DateTime

泛型缓存

线程池

匿名线程

NPIO操作excel

不同类相同属性转换(动态拼接表达式目录树+泛型缓存)(性能超过automapper)

IO文件操作

递归找出所有文件

MD5加密(加密,摘要)

SHA256(加密,摘要)


配置

IIS

1. 6.0以上程序池用集成
2. IIS需要托管的程序添加everyone权限才能读取
3. 运行core时需要安装Hosting

程序设计

1.配置文件路由地址最好新建一个类进行访问,存储


程序

Parallel并行执行任务,最好配合线程安全List

            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            Parallel.For(0, nums.Length, (i) =>
            {
                Console.WriteLine("针对数组索引{0}对应的那个元素{1}的一些工作代码……ThreadId={2}", i, nums[i], Thread.CurrentThread.ManagedThreadId);
            });

线程安全的list

// 线程安全的list
            ConcurrentBag<TestEntity> datas=new ConcurrentBag<TestEntity>();

Winform跨线程更新UI界面

//子线程不能操作控件,委托给主线程操作
//this.Invoke
this.Invoke(new Action(() =>
{
    label.Text = sNumber;
}));

读取Json配置文件

//--------------------------JSON-------------------------------
{
 "name": "wen",
 "age": 26,
 "family": {
  "mother": {
   "name": "娘",
   "age": 55
  },
  "father": {
   "name": "爹",
   "age": 56
  }
 }
}
//-----------------------Program------------------------------
需要 Nuget 两个类库:
  ①Microsoft.Extensions.Configuration
  ②Microsoft.Extensions.Configuration.Json
//添加 json 文件路径
      var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
      .AddJsonFile("appsettings.json");
      //创建配置根对象
      var configurationRoot = builder.Build();
 
      //取配置根下的 name 部分
      var nameSection = configurationRoot.GetSection("name");
      //取配置根下的 family 部分
      var familySection = configurationRoot.GetSection("family");
      //取 family 部分下的 mother 部分下的 name 部分
      var motherNameSection = familySection.GetSection("mother").GetSection("name");
      //取 family 部分下的 father 部分下的 age 部分
      var fatherAgeSection = familySection.GetSection("father").GetSection("age");
      //Value 为文本值
      Console.WriteLine($"name: {nameSection.Value}");
      Console.WriteLine($"motherName: {motherNameSection.Value}");
      Console.WriteLine($"fatherAge: {fatherAgeSection.Value}");

DateTime

DateTime.Now.ToString("yyyy-M-d-H-m-s")


泛型缓存

static class DataCache<TModel>
{
     /// <summary>
     /// 初始化数据
     /// </summary>
     static DataCache()
     {
         Cache = new List<TModel>();
     }
     public static List<TModel> Cache { get; set; }
 }


线程池

//配置线程池,如非必要可以不必配置,直接调用 ThreadPool.QueueUserWorkItem
{
    int workerThreads;
    int portThreads;
    //--------------------------获取处于活动状态的线程池请求的数目------------------------------ 
    ThreadPool.GetMaxThreads(out workerThreads, out portThreads);
    Console.WriteLine($"设置前,线程池中辅助线程最大数:{workerThreads};异步I/O线程的最大数:{portThreads}");

    //--------------------------设置处于活动状态的线程池请求的数目------------------------------ 
    workerThreads = 10;//设置辅助线程的最大数
    portThreads = 500;//设置线程池中异步I/O线程的最大数
    ThreadPool.SetMaxThreads(workerThreads, portThreads);
    Console.WriteLine($"设置后,线程池中辅助线程最大数:{workerThreads};异步I/O线程的最大数:{portThreads}");

    int minWorker, minIOC;

    //--------------------------获取线程池在新请求预测中维护的默认空闲线程数------------------------------ 
    ThreadPool.GetMinThreads(out minWorker, out minIOC);
    Console.WriteLine($"设置前,线程池维护的空闲辅助线程的最小数:{minWorker};线程池维护的空闲异步I/O线程的最小数:{minIOC}");//在控制台中显示线程池的默认空闲线程数

    //--------------------------设置线程池在新请求预测中维护的默认空闲线程数------------------------------
    minWorker = 4;//设置线程池维护的空闲辅助线程的最小数
    minIOC = 10;//设置线程池维护的空闲异步I/O线程的最小数

    ThreadPool.SetMinThreads(minWorker, minIOC);
    Console.WriteLine($"设置前,线程池维护的空闲辅助线程的最小数:{minWorker};线程池维护的空闲异步I/O线程的最小数:{minIOC}");
}
//------------------------------------执行线程------------------------------------ 
ThreadPool.QueueUserWorkItem(new WaitCallback(p => { Console.WriteLine("asd"); }));

匿名线程

Thread theader = new Thread(new ThreadStart(new Action(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("我是新建的子线程.....");
            })));
            theader.Start();

NPIO操作excel

HSSFWorkbook wk = new HSSFWorkbook();//这是用于后缀名是.xls的excel文件的操作

//XSSFWorkbook wk = new XSSFWorkbook();  这是用于后缀名是.xlsx的excel文件的操作

using (FileStream fs2 = new FileStream("2.xls", FileMode.OpenOrCreate))
{
    try
    {
        ISheet isheet = wk.CreateSheet("Sheet1");//这是创建一个工作簿,其名字位 "Sheet1"
        IRow row;
        ICell cell;
        int rowIndex = 0;
        int cellIndex = 0;
        for (rowIndex = 0; rowIndex < 10; rowIndex++)
        {
            row = isheet.CreateRow(rowIndex);//这个函数是创建该工作簿的第rowIndex行,并不是创建rowIndex行,从第0行开始    
            for (cellIndex = 0; cellIndex < 10; cellIndex++)
            {
                cell = row.CreateCell(cellIndex);//这个函数是创建该工作簿第cellIndex列(即某个单元格),从第0列开始
                cell.SetCellValue(1);//这个函数就是向第rowIndex行和第cellIndex列放数据,此处放的是int型的数字1
            }
        }
    }
    catch (Exception)
    {
        return false;
        throw;
    }
    finally
    {
        wk.Write(fs2);//向打开的这个2.xls文件中写入上面添加的数据  
        wk.Close();//这就是释放资源  (详细知识请参考其它资料,这里不做解释)
    }
}


不同类相同属性转换(动态拼接表达式目录树+泛型缓存)(性能超过automapper)

    /// <summary>
    /// 生成表达式目录树  泛型缓存
    /// </summary>
    /// <typeparam name="TIn"></typeparam>
    /// <typeparam name="TOut"></typeparam>
    ///用法 ExpressionGenericMapper<People, PeopleCopy>.Trans(people);
    public class ExpressionGenericMapper<TIn, TOut>//Mapper`2
    {
        private static Func<TIn, TOut> _FUNC = null;
        static ExpressionGenericMapper()
        {
            ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
            List<MemberBinding> memberBindingList = new List<MemberBinding>();
            foreach (var item in typeof(TOut).GetProperties())
            {
                MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                MemberBinding memberBinding = Expression.Bind(item, property);
                memberBindingList.Add(memberBinding);
            }
            foreach (var item in typeof(TOut).GetFields())
            {
                MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));
                MemberBinding memberBinding = Expression.Bind(item, property);
                memberBindingList.Add(memberBinding);
            }
            MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
            Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[]
            {
                    parameterExpression
            });
            _FUNC = lambda.Compile();//拼装是一次性的
        }
        public static TOut Trans(TIn t)
        {
            return _FUNC(t);
        }
    }

IO文件操作

//-------------------------------Directory--------------------------------------

//如果目录文件不存在(检测目录文件是否存在)
if (!Directory.Exists(LogPath))

//一次性创建全部的子路径
DirectoryInfo directoryInfo = Directory.CreateDirectory(LogPath);

//移动  原文件夹就不在了
Directory.Move(LogPath, LogMovePath);

//删除
Directory.Delete(LogMovePath);

//-------------------------------File------------------------------------------
//File打开文件会独占

//Path.Combine将两个字符串组合成一个路径。
string fileName = Path.Combine(LogPath, "log.txt");
string fileNameCopy = Path.Combine(LogPath, "logCopy.txt");
string fileNameMove = Path.Combine(LogPath, "logMove.txt");
bool isExists = File.Exists(fileName);
if (!isExists)
{
    Directory.CreateDirectory(LogPath);//创建了文件夹之后,才能创建里面的文件
    
    //写入方式1 如果没有文件AppendText会创建文件(推荐直接用字符串写)
    //流写入器(创建/打开文件并写入)
    using (StreamWriter sw = File.AppendText(fileName))
    {
        string msg = "今天是Course6IOSerialize,今天上课的人有55个人";
        sw.WriteLine(msg);
        sw.Flush();
    }
    
    //写入方式2    流写入器(创建/打开文件并写入)
    using (StreamWriter sw = File.AppendText(fileName))
    {
        string name = "0987654321";
        //字符串转换成byte再写入
        byte[] bytes = Encoding.Default.GetBytes(name);
        sw.BaseStream.Write(bytes, 0, bytes.Length);
        sw.Flush(); 
    }

//-------------------------------读取文件------------------------------------------
//File.ReadAllLines读取文本中的所有行,每一行为一个result 
    foreach (string result in File.ReadAllLines(fileName))
    {
        Console.WriteLine(result);
    }
    
    //File.ReadAllText会直接读取所有内容
    string sResult = File.ReadAllText(fileName);
    
    //File.ReadAllBytes读取所有内容转换成byte数组
    Byte[] byteContent = File.ReadAllBytes(fileName);
    //再转换成字符串
    string sResultByte = System.Text.Encoding.UTF8.GetString(byteContent);

    //文本内容太长,则分批读取
    using (FileStream stream = File.OpenRead(fileName))
    {
        int length = 5;
        int result = 0;

        do
        {
            byte[] bytes = new byte[length];
            result = stream.Read(bytes, 0, 5);
            for (int i = 0; i < result; i++)
            {
                Console.WriteLine(bytes[i].ToString());
            }
        }
        while (length == result);
    }

    //文件拷贝
    File.Copy(fileName, fileNameCopy);
    //文件移动
    File.Move(fileName, fileNameMove);
    //文件删除
    File.Delete(fileNameCopy);
    File.Delete(fileNameMove);//尽量不要delete



    {
    //获取硬盘名称,空间等信息
    DriveInfo[] drives = DriveInfo.GetDrives();

    	{//DriveInfo
	    DriveInfo[] drives = DriveInfo.GetDrives();
	
	    foreach (DriveInfo drive in drives)
	    {
	        if (drive.IsReady)
	            Console.WriteLine("类型:{0} 卷标:{1} 名称:{2} 总空间:{3} 剩余空间:{4}", drive.DriveType, drive.VolumeLabel, drive.Name, drive.TotalSize, drive.TotalFreeSpace);
	        else
	            Console.WriteLine("类型:{0}  is not ready", drive.DriveType);
	    }
	}

{
    Console.WriteLine(Path.GetDirectoryName(LogPath));  //返回目录名,需要注意路径末尾是否有反斜杠对结果是有影响的
    Console.WriteLine(Path.GetDirectoryName(@"d:\\abc")); //将返回 d:\
    Console.WriteLine(Path.GetDirectoryName(@"d:\\abc\"));// 将返回 d:\abc
    Console.WriteLine(Path.GetRandomFileName());//将返回随机的文件名
    Console.WriteLine(Path.GetFileNameWithoutExtension("d:\\abc.txt"));// 将返回abc
    Console.WriteLine(Path.GetInvalidPathChars());// 将返回禁止在路径中使用的字符
    Console.WriteLine(Path.GetInvalidFileNameChars());//将返回禁止在文件名中使用的字符
    Console.WriteLine(Path.Combine(LogPath, "log.txt"));//合并两个路径
}

递归找出所有文件

    /// <summary>
    /// 递归的编程技巧
    /// 表达式目录树---递归--无法预测深度的查找--有重复的动作---就会用上递归---自己调用自己
    /// 
    /// 递归看别人写很简单,自己动手有点不好做,经常想不到
    /// 1 递归一定要有跳出条件
    /// 2 递归对内存有些压力
    /// 3 递归执行速度快,请谨慎使用
    /// </summary>
    public class Recursion
    {
        /// <summary>
        /// 找出全部的子文件夹
        /// </summary>
        /// <param name="rootPath">根目录</param>
        /// <returns></returns>
        public static List<DirectoryInfo> GetAllDirectory(string rootPath)
        {
            if (!Directory.Exists(rootPath))
                return new List<DirectoryInfo>();

            List<DirectoryInfo> directoryList = new List<DirectoryInfo>();//容器
            DirectoryInfo directory = new DirectoryInfo(rootPath);//root文件夹
            directoryList.Add(directory);

            return GetChild(directoryList, directory);
        }

        /// <summary>
        /// 完成 文件夹--子目录--放入集合
        /// </summary>
        /// <param name="directoryList"></param>
        /// <param name="directoryCurrent"></param>
        /// <returns></returns>
        private static List<DirectoryInfo> GetChild(List<DirectoryInfo> directoryList, DirectoryInfo directoryCurrent)
        {
            var childArray = directoryCurrent.GetDirectories();
            if (childArray != null && childArray.Length > 0)
            {
                directoryList.AddRange(childArray);
                foreach (var child in childArray)
                {
                    GetChild(directoryList, child);
                }
            }
            return directoryList;
        }

    }

MD5加密(加密,摘要)

Des,RSA,MD5整个程序集(https://pan.baidu.com/s/1sj0aR8SsvsMn6b5J_6LEQA

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyEncrypt
{
    /// <summary>
    /// 不可逆加密
    /// 1 防止被篡改
    /// 2 防止明文存储
    /// 3 防止抵赖,数字签名
    /// </summary>
    public class MD5Encrypt
    {
        #region MD5
        /// <summary>
        /// MD5加密,和动网上的16/32位MD5加密结果相同,
        /// 使用的UTF8编码
        /// </summary>
        /// <param name="source">待加密字串</param>
        /// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>
        /// <returns>加密后的字串</returns>
        public static string Encrypt(string source, int length = 32)//默认参数
        {
            if (string.IsNullOrEmpty(source)) return string.Empty;
            HashAlgorithm provider = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;
            byte[] bytes = Encoding.UTF8.GetBytes(source);//这里需要区别编码的
            byte[] hashValue = provider.ComputeHash(bytes);
            StringBuilder sb = new StringBuilder();
            switch (length)
            {
                case 16://16位密文是32位密文的9到24位字符
                    for (int i = 4; i < 12; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
                case 32:
                    for (int i = 0; i < 16; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
                default:
                    for (int i = 0; i < hashValue.Length; i++)
                    {
                        sb.Append(hashValue[i].ToString("x2"));
                    }
                    break;
            }
            return sb.ToString();
        }
        #endregion MD5

        #region MD5摘要
        /// <summary>
        /// 获取文件的MD5摘要
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        ///string md5Abstract1 = MD5Encrypt.AbstractFile(@"D:\副本.rar");
        public static string AbstractFile(string fileName)
        {
            using (FileStream file = new FileStream(fileName, FileMode.Open))
            {
                return AbstractFile(file);
            }
        }
        /// <summary>
        /// 根据stream获取文件摘要
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string AbstractFile(Stream stream)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(stream);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
        #endregion
    }
}

SHA256(加密,摘要)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyEncrypt
{
    public class SHA256Encrypt
    {
        #region SHA加密
        /// <summary>
        /// SHA256加密
        /// </summary>
        /// <param name="data">加密的数据</param>
        /// <returns>加密后的数据</returns>
        public static string Encrypt(string data)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            byte[] hash = SHA256Managed.Create().ComputeHash(bytes);

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                builder.Append(hash[i].ToString("X2"));
            }

            return builder.ToString();
        }
        #endregion

        #region SHA256摘要
        /// <summary>
        /// SHA256文件内容摘要
        /// </summary>
        /// <param name="stream"></param>
        /// <returns>加密后的字符串</returns>
        /// 用法 => string str = SHA256Encrypt.AbstractFile(@"D:\副本.rar");
        public static string AbstractFile(Stream stream)
        {
            SHA256 sha256 = new SHA256CryptoServiceProvider();
            byte[] retVal = sha256.ComputeHash(stream);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
        /// <summary>
        /// SHA256文件内容摘要
        /// </summary>
        /// <param name="stream"></param>
        /// <returns>加密后的字符串</returns>
        public static string AbstractFile(string fileName)
        {
            using (FileStream file = new FileStream(fileName, FileMode.Open))
            {
                return AbstractFile(file);
            }
        }
        #endregion
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值