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

一、配置文件读写类

用于在开发时候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.hqwc.cn/news/596032.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode 1017. 负二进制转换

解题思路 相关代码 class Solution {public String baseNeg2(int n) {if(n0) return "0";String s"";while(n!0)if(Math.abs(n)%20){nn/(-2);ss0;}else{ss1; n (n-1)/(-2);}String t reverse(s);return t;}public String reverse(String s){Str…

ZYNQ学习Linux 基础外设的使用

基本都是摘抄正点原子的文章&#xff1a;《领航者 ZYNQ 之嵌入式Linux 开发指南 V3.2.pdf》&#xff0c;因初次学习&#xff0c;仅作学习摘录之用&#xff0c;有不懂之处后续会继续更新~ 工程的创建参考&#xff1a;《ZYNQ学习之Petalinux 设计流程实战》 一、GPIO 之 LED 的使…

自定义实现shell/bash

文章目录 函数和进程之间的相似性shell打印提示符&#xff0c;以及获取用户输入分割用户的输入判断是否是内建命令执行相关的命令 全部代码 正文开始前给大家推荐个网站&#xff0c;前些天发现了一个巨牛的 人工智能学习网站&#xff0c; 通俗易懂&#xff0c;风趣幽默&#…

(二)小案例银行家应用程序-创建DOM元素

● 上图的数据很明显是从我们账户数组中拿到了&#xff0c;我们刚刚学习了forEach&#xff0c;所以我们使用forEach来创建我们的DOM元素&#xff1b; const displayMovements function (movements) {movements.forEach((mov, i) > {const type mov > 0 ? deposit : w…

通用开发技能系列:Scrum、Kanban等敏捷管理策略

云原生学习路线导航页&#xff08;持续更新中&#xff09; 本文是 通用开发技能系列 文章&#xff0c;主要对编程通用技能 Scrum、Kanban等敏捷管理策略 进行学习 1.什么是敏捷开发 敏捷是一个描述软件开发方法的术语&#xff0c;它强调增量交付、团队协作、持续规划和持续学习…

github本地仓库push到远程仓库

1.从远程仓库clone到本地 2.生成SSH秘钥&#xff0c;为push做准备 在Ubuntu命令行输入一下内容 [rootlocalhost ~]# ssh-keygen -t rsa < 建立密钥对&#xff0c;-t代表类型&#xff0c;有RSA和DSA两种 Generating public/private rsa key pair. Enter file in whi…

HTTP详解及代码实现

HTTP详解及代码实现 HTTP超文本传输协议 URL简述状态码常见的状态码 请求方法请求报文响应报文HTTP常见的HeaderHTTP服务器代码 HTTP HTTP的也称为超文本传输协议。解释HTTP我们可以将其分为三个部分来解释&#xff1a;超文本&#xff0c;传输&#xff0c;协议。 超文本 加粗样…

上线部署流程

音频地址&#xff1a;上线部署流程_小蒋聊技术在线播放免费听 - 喜马拉雅手机版 时间&#xff1a;2024年04月06日 作者&#xff1a;小蒋聊技术 邮箱&#xff1a;wei_wei10163.com 微信&#xff1a;wei_wei10 背景 大家好&#xff0c;欢迎来到小蒋聊技术&#xff0c;小蒋准…

正排索引 vs 倒排索引 - 搜索引擎具体原理

阅读导航 一、正排索引1. 概念2. 实例 二、倒排索引1. 概念2. 实例 三、正排 VS 倒排1. 正排索引优缺点2. 倒排索引优缺点3. 应用场景 三、搜索引擎原理1. 宏观原理2. 具体原理 一、正排索引 1. 概念 正排索引是一种索引机制&#xff0c;它将文档或数据记录按照某种特定的顺序…

Python 基于列表实现的通讯录管理系统(有完整源码)

目录 通讯录管理系统 PersonInformation类 ContactList类 menu函数 main函数 程序的运行流程 完整代码 运行示例 通讯录管理系统 这是一个基于文本的界面程序&#xff0c;用户可以通过命令行与之交互&#xff0c;它使用了CSV文件来存储和读取联系人信息&#xff0c;这…

开源数学计算软件Maxima基础学习

在Maxima中计算四则运算可以直接使用数学符号&#xff0c;在输入完公式后使用 EnterShift 快捷键进行计算 (%i1)11 输出 (%o1)2 这里面的 (%i1) 代表 input1 第1号输入&#xff0c;(%o1) 代表 output1 第1号输出。在执行计算后&#xff0c;(%i1)11 这一行命令后会出现一个…

2_5.Linux存储的基本管理

实验环境&#xff1a; 系统里添加两块硬盘 ##1.设备识别## 设备接入系统后都是以文件的形式存在 设备文件名称&#xff1a; SATA/SAS/USB /dev/sda,/dev/sdb ##s SATA, dDISK a第几块 IDE /dev/hd0,/dev/hd1 ##h hard VIRTIO-BLOCK /de…