C#开发中一些常用的工具类分享

news2024/10/5 23:29:21

一、配置文件读写类

用于在开发时候C#操作配置文件读写信息

  • 1、工具类 ReadIni 代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace TcpServer
{
    public class ReadIni
    {
        [DllImport("kernel32")]// 读配置文件方法的6个参数:所在的分区(section)、 键值、     初始缺省值、   StringBuilder、  参数长度上限 、配置文件路径
        public static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);
        [DllImport("kernel32")]//写入配置文件方法的4个参数:  所在的分区(section)、  键值、     参数值、       配置文件路径
        private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);

        public static string FileNmae = "SysConfig.ini";
        /*读配置文件*/
        public static string GetValue(string section, string key)
        {          

            string fileName = Directory.GetCurrentDirectory() + "/" + ReadIni.FileNmae;
            if (File.Exists(fileName))  //检查是否有配置文件,并且配置文件内是否有相关数据。
            {
                StringBuilder sb = new StringBuilder(255);               
                GetPrivateProfileString(section, key, "配置文件不存在,读取未成功!", sb, 255, fileName);
                return sb.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /*写配置文件*/
        public static void SetValue(string section, string key, string value)
        {            
            string fileName = Directory.GetCurrentDirectory() + "/" + ReadIni.FileNmae;
            WritePrivateProfileString(section, key, value, fileName); // 路径会自动创建
        }
    }
}
  • 2、使用方法
// 自定义配置文件名称  
ReadIni.FileNmae ="Config.ini"; // 默认SysConfig.ini
// 设置配置文件内容
 ReadIni.SetValue("配置", "测试","王小宝好");
 // 读取配置文件内容
 string value = ReadIni.GetValue("配置","测试");

3、效果
在这里插入图片描述

二、日志记录类

在项目开发中我们经常要对业务进行日志记录,方便出现问题后对于故障的排查。这里我们使用C#实现了简单的日志记录功能。

  • 1、日志记录类代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TcpServer
{
    public class Logger
    {
        private string logPath;
        private string DirPath;

        public Logger(string path)
        {
            DirPath = path;
        }
        public Logger()
        {
            DirPath = Directory.GetCurrentDirectory()+"/logs/"+DateTime.Now.ToString("yyyyMMdd");            
        }

        public void LogInfo(string message)
        {
            if (!Directory.Exists(DirPath)) { Directory.CreateDirectory(DirPath); }
            logPath = DirPath + "/log-info.log";
            Log("INFO", message);
        }

        public void LogWarning(string message)
        {
            if (!Directory.Exists(DirPath)) { Directory.CreateDirectory(DirPath); }
            logPath = DirPath + "/log-warning.log";
            Log("WARNING", message);
        }

        public void LogError(string message)
        {
            if (!Directory.Exists(DirPath)) { Directory.CreateDirectory(DirPath); }
            logPath =DirPath+ "/log-error.log";
            Log("ERROR", message);
        }

        private void Log(string level, string message)
        {
            string logEntry = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - {level} - {message}{Environment.NewLine}";
            File.AppendAllText(logPath, logEntry);
        }
    }
}

  • 2、使用方法
Logger Log = new Logger();
Log.LogInfo("记录一条日志信息");
Log.LogWarning("记录警告日志");
Log.LogError("记录错误日志");
  • 3、记录效果
    在这里插入图片描述

三、数据缓存类

数据缓存类是一个用C#实现的对数据进行缓存的简单功能

  • 1、数据缓存类实现代码
using System;
using System.Collections.Generic;

namespace TcpServer
{

    public class CacheHelper<TKey, TValue>
    {
        private readonly Dictionary<TKey, CachedItem> _cache = new Dictionary<TKey, CachedItem>();      

        public CacheHelper()
        {
            
        }

        public void Set(TKey key, TValue value,int tTime= 3600)
        {
            _cache[key] = new CachedItem { ExpTime= TimeSpan.FromSeconds(tTime), Created = DateTime.UtcNow, Value = value };
        }
       



        public bool TryGet(TKey key, out TValue value)
        {
            CachedItem cachedItem;
            if (_cache.TryGetValue(key, out cachedItem) && cachedItem.IsValid)
            {
                value = (TValue)cachedItem.Value;
                return true;
            }
            value = default(TValue);
            return false;
        }

        public bool Remove(TKey key)
        {
            return _cache.Remove(key);
        }

        public void Clear()
        {
            _cache.Clear();
        }

        // 辅助类,用于跟踪缓存项的创建时间和有效期
        private class CachedItem
        {
            public TimeSpan ExpTime { get; set; }
            
            public DateTime Created { get; set; }
            
            public object Value { get; set; }

            public bool IsValid
            {
                get
                {
                    return DateTime.UtcNow - Created < ExpTime;
                }
            }
        }
    }
}
  • 2、使用方法
 CacheHelper<string, object> cache = new CacheHelper<string, object>(); 
 // 设置缓存  缓存20秒 
 cache.Set("key1", "value1",20);
 // 读取缓存
  object value = string.Empty;
  if (cache.TryGet("key1", out  value))
  {      
      return value;
  }
  
  • 3、使用效果需要用心体会

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1564960.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何将本地仓库放到远程仓库中

在我们仓库创建好之后&#xff0c;我们复制好ssh 接着我们需要使用git remote add<shortname><url>这个命令 shortname就是我们远程仓库的别名 接着使用git remote -v这个命令查看一下目前远程仓库的别名和地址 原本还有一个指令git branch -M main 指定分支的名…

全志 Linux Qt

一、简介 本文介绍基于 buildroot 文件系统的 QT 模块的使用方法&#xff1a; • 如何在 buildroot 工具里编译 QT 动态库&#xff1b; • 编译及运行 qt_demo 应用程序&#xff1b; • 适配过程遇到的问题。 二、QT动态库编译 在项目根路径执行 ./build.sh buildroot_menuc…

酷开科技智慧AI让酷开系统大显身手!

时代的浪潮汹涌而至&#xff0c;人工智能作为技术革新和产业变革的重要引擎&#xff0c;正深刻地影响着各行各业。在科技的海洋中&#xff0c;AI技术正逐渐渗透到我们的日常生活中&#xff0c;为我们带来前所未有的便捷和智慧。酷开科技用技术探索智慧AI&#xff0c;别看它只是…

MySQL 中将使用逗号分隔的字段转换为多行数据

在我们的实际开发中&#xff0c;经常需要存储一些字段&#xff0c;它们使用像, - 等连接符进行连接。在查询过程中&#xff0c;有时需要将这些字段使用连接符分割&#xff0c;然后查询多条数据。今天&#xff0c;我们将使用一个实际的生产场景来详细解释这个解决方案。 场景介绍…

JeeSite Vue3:前端开发控制实现基于身份角色的权限验证

随着技术的飞速发展&#xff0c;前端开发技术日新月异。在这个背景下&#xff0c;JeeSite Vue3 作为一个基于 Vue3、Vite、Ant-Design-Vue、TypeScript 和 Vue Vben Admin 的前端框架&#xff0c;引起了广泛关注。它凭借其先进的技术栈和丰富的功能模块&#xff0c;为初学者和团…

【教程】Kotlin语言学习笔记(五)——Lambda表达式与条件控制

写在前面&#xff1a; 如果文章对你有帮助&#xff0c;记得点赞关注加收藏一波&#xff0c;利于以后需要的时候复习&#xff0c;多谢支持&#xff01; 【Kotlin语言学习】系列文章 第一章 《认识Kotlin》 第二章 《数据类型》 第三章 《数据容器》 第四章 《方法》 第五章 《L…

LangChain-03 astream_events 流输出

内容简介 尝试用 FAISS 或 DocArrayInMemorySearch 将数据向量化后检索astream_events 的效果为 |H|arrison| worked| at| Kens|ho|.|| 安装依赖 # 之前的依赖即可 pip install --upgrade --quiet langchain-core langchain-community langchain-openai # Win或Linux用户可…

算法学习——LeetCode力扣动态规划篇3(494. 目标和、474. 一和零、518. 零钱兑换 II)

算法学习——LeetCode力扣动态规划篇3 494. 目标和 494. 目标和 - 力扣&#xff08;LeetCode&#xff09; 描述 给你一个非负整数数组 nums 和一个整数 target 。 向数组中的每个整数前添加 ‘’ 或 ‘-’ &#xff0c;然后串联起所有整数&#xff0c;可以构造一个 表达式 …

【xinference】(8):在autodl上,使用xinference部署qwen1.5大模型,速度特别快,同时还支持函数调用,测试成功!

1&#xff0c;关于xinference https://www.bilibili.com/video/BV14x421U74t/ 【xinference】&#xff08;8&#xff09;&#xff1a;在autodl上&#xff0c;使用xinference部署qwen1.5大模型&#xff0c;速度特别快&#xff0c;同时还支持函数调用&#xff0c;测试成功&#…

系统IO函数接口

目录 前言 一. man手册 1.1 man手册如何查询 1.2 man手册基础 二.系统IO函数接口 三.open打开文件夹 3.1 例1 open打开文件 3.2 open打开文件代码 3.3 例2 创建文件 四.write写文件 4.1 write写文件 五. read读文件 5.1 read读文件与偏移 5.2 偏移细节 5.3 read读文件代码 六.复…

1,static 关键字.Java

目录 1.概述 2.定义格式和使用 2.1 静态变量及其访问 2.2 实例变量及其访问 2.3 静态方法及其访问 2.4 实例方法及其访问 3.小结 1.概述 static表示静态&#xff0c;是Java中的一个修饰符&#xff0c;可以修饰成员方法&#xff0c;成员变量。被static修饰后的&#xff…

STM32CubeMX配置步骤详解零 —— 引言

引子 初识 笔者接触STM32系列MCU有些年头了。初次接触是2015年&#xff0c;那时是在第二空间&#xff08;北京&#xff09;科技有限公司上班&#xff0c;是以STM32F407&#xff08;后缀好像是RGT6或ZGT6&#xff0c;记得不是很清楚了&#xff09;为主芯片做VR头戴式设备&…

40道Java经典面试题总结

1、在 Java 中&#xff0c;什么时候用重载&#xff0c;什么时候用重写&#xff1f; &#xff08;1&#xff09;重载是多态的集中体现&#xff0c;在类中&#xff0c;要以统一的方式处理不同类型数据的时候&#xff0c;可以用重载。 &#xff08;2&#xff09;重写的使用是建立…

githacker安装使用

githack下载不了文件&#xff0c;换个工具&#xff01; 项目地址 WangYihang/GitHacker: &#x1f577;️ A .git folder exploiting tool that is able to restore the entire Git repository, including stash, common branches and common tags. (github.com) 安装 pyth…

光伏行业项目管理系统解决方案!企智汇光伏项目管理系统!

光伏行业项目管理系统解决方案旨在通过整合和优化项目管理流程&#xff0c;提高光伏项目的执行效率和质量。以下是企智汇软件详细的光伏行业项目管理系统解决方案的框架&#xff1a; 一、系统概述 企智汇光伏行业项目管理系统是一个集项目规划、执行、监控和收尾于一体的综合…

Vue3:用Pinia的storeToRefs结构赋值store数据

一、情景描述 我们学习了Pinia之后&#xff0c;知道&#xff0c;数据是配置在Pinia的state里面的。 那么&#xff0c;如果有多个字段需要取出来使用&#xff0c;并且不丢失数据的响应式&#xff0c;如何优雅的操作了&#xff1f; 这里就用到了Pinia的storeToRefs函数 二、案…

【CANN训练营笔记】AscendCL图片分类应用(C++实现)

样例介绍 基于PyTorch框架的ResNet50模型&#xff0c;对*.jpg图片分类&#xff0c;输出各图片所属分类的编号、名称。 环境介绍 华为云AI1s CPU&#xff1a;Intel Xeon Gold 6278C CPU 2.60GHz 内存&#xff1a;8G NPU&#xff1a;Ascend 310 环境准备 下载驱动 wget ht…

CAPL实现关闭TCP连接的几种方式以及它们的区别

在讲正文前,我们有必要复习下关闭TCP连接的过程:四次挥手。 假设A和B建立TCP连接并进行数据传输,当A的数据发送完后,需要主动发起断开连接的请求: A发送FIN报文,发起断开连接的请求B收到FIN报文后,首先回复ACK确认报文B把自己的数据发送完,发送FIN报文,发起断开连接的…

探索网红系统功能菜单架构的设计与优化

随着社交媒体和数字化内容的普及&#xff0c;网红经济正在成为新兴的产业。在网红经济体系中&#xff0c;网红系统的功能菜单架构对于平台的用户体验和运营效率至关重要。本文将深入探讨网红系统功能菜单架构的设计与优化&#xff0c;为网红经济的发展提供新的思路和方法。 --…

HWOD:自守数

一、知识点 break只会结束最里面的一层循环 int型数按位比较的时候&#xff0c;可以直接求余比较&#xff0c;无需转换为char型数组后再按下标比较 二、题目 1、描述 自守数是指一个数的平方的尾数等于该数自身的自然数。例如&#xff1a;25^2 625&#xff0c;76^2 5776…