public static byte[] HexStrToBytes(string text)
{
//把输入框中的文本转成字符串数组
string[] hexStrs = text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
//转byte[]
byte[] data = new byte[hexStrs.Length];
for (int i = 0; i < hexStrs.Length; i++)
{
data[i] = Convert.ToByte(hexStrs[i], 16);
}
return data;
}
public static string BytesToHexStr(byte[] buffer, int length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++)
{
sb.Append(buffer[i].ToString("X2")).Append(" ");
}
return sb.ToString();
}
public static short BytesToShort(byte b1, byte b2)
{
short us = (short)(((b1 & 0xFF) << 8) | (b2 & 0xFF));
// ushort us = (ushort)(((b1 & 0xFF) << 8) | (b2 & 0xFF));
return us;
}
///
/// 生成crc校验码
///
/// 校验数据,字节数组
/// 字节0是高8位,字节1是低8位
public static byte[] CreateCRC16(byte[] data)
{
//crc计算赋初始值
int crc = 0xffff;
for (int i = 0; i < data.Length; i++)
{
crc ^= data[i];
for (int j = 0; j < 8; j++)
{
int temp;
temp = crc & 1;
crc >>= 1;
crc &= 0x7fff;
if (temp == 1)
{
crc ^= 0xa001;
}
crc &= 0xffff;
}
}
//CRC寄存器的高低位进行互换
byte[] crc16 = new byte[2];
//CRC寄存器的高8位变成低8位,
crc16[1] = (byte)((crc >> 8) & 0xff);
//CRC寄存器的低8位变成高8位
crc16[0] = (byte)(crc & 0xff);
return crc16;
}
///
/// 把data数组追加校验码数组,生成新的数组
///
///
///
public static byte[] AddCrc16(byte[] data)
{
//校验码
byte[] crcs = CreateCRC16(data);
//创建一个新的数组,合并data数组和校验码数组
byte[] buffer = new byte[crcs.Length + data.Length];
for(int i = 0; i < buffer.Length; i++)
{
if (i < data.Length)
{
buffer[i] = data[i];
}
else
{
buffer[i] = crcs[i - data.Length];
}
}
return buffer;
}
///
/// 判断校验码是否正确
///
/// 数据
/// 读取到的数据长度
///
public static bool CompareCrc(byte[] buffer, int length)
{
//01 03 08 00 1e 00 27 01 ce 01 18 3e 48
//读取校验码前面的数据,生成新的校验码,与发送过的校验码做对比
byte[] temps = new byte[length - 2];
Array.Copy(buffer, 0, temps, 0, temps.Length);
byte[] crcs = CreateCRC16(temps);
return crcs[1] == buffer[length - 1] && crcs[0] == buffer[length - 2];
}
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace CoreDevice { ///
/// Ini文件操作工具类 /// public class IniFileUtil { ////// ini文件完整路径 /// public string FileName { get; set; } ////// 实例化 /// /// ini文件完整路径 public IniFileUtil(string fileName) { this.FileName = fileName; } #region 读取 ////// 读取ini文件数据 /// /// 段名 /// 键名 ///public string Read(string sectionName, string keyName) { return Read(sectionName, keyName, FileName); } /// /// 读取ini文件数据 /// /// 段名 /// 键名 /// 当读取到的数据为空时的默认值 ///public string ReadStr(string sectionName, string keyName, string defaultValue) { string value = Read(sectionName, keyName); if (string.IsNullOrEmpty(value)) { return defaultValue; } else { return value; } } /// /// 读取ini文件数据,转成int类型 /// /// 段名 /// 键名 /// 转不成int类型的默认值 ///public int ReadInt(string sectionName, string keyName, int defaultValue) { string str = Read(sectionName, keyName); if (int.TryParse(str, out int value)) { return value; } else { return defaultValue; } } /// /// 读取ini文件数据,转成bool类型 /// /// 段名 /// 键名 /// 转不成bool类型的默认值 ///public bool ReadBool(string sectionName, string keyName, bool defaultValue) { string str = Read(sectionName, keyName); if (bool.TryParse(str, out bool value)) { return value; } else { if (str == "1" || str.ToUpper() == "OK" || str.ToUpper() == "YES" || str.ToUpper() == "ON") { return true; } else if (str == "0" || str.ToUpper() == "NO" || str.ToUpper() == "OFF") { return false; } else { return defaultValue; } } } /// /// 读取ini文件数据,转成double类型 /// /// 段名 /// 键名 /// 转不成double类型的默认值 ///public double ReadDouble(string sectionName, string keyName, double defaultValue) { string str = Read(sectionName, keyName); if (double.TryParse(str, out double value)) { return value; } else { return defaultValue; } } #endregion #region 写入 /// /// 写入ini文件数据 /// /// 段名 /// 键名 /// 值 ///public int Write(string sectionName, string keyName, string value) { return Write(sectionName, keyName, value, FileName); } /// /// 写入ini文件数据 /// /// 段名 /// 键名 /// 值 ///public int Write(string sectionName, string keyName, bool value) { return Write(sectionName, keyName, value ? "1" : "0"); } #endregion #region 静态方法 /// /// 写入数据 /// /// 段名 /// 键名 /// 值 ///public static int Write(string sectionName, string keyName, string value, string fileName) { return WritePrivateProfileString(sectionName, keyName, value, fileName); } /// /// 读取数据 /// /// 段名 /// 键名 ///public static string Read(string sectionName, string keyName, string fileName) { StringBuilder sb = new StringBuilder(512); GetPrivateProfileString(sectionName, keyName, string.Empty, sb, 512, fileName); return sb.ToString(); } /* * 引用c/c++语言的dll时,方法名称不是随便命名的,要跟c/c++ dll里面的方法名称一样 * */ /// /// ini配置文件写入配置,如果存在则修改,如果不存在则新增 /// /// 段名 /// 键名 /// 值 /// ini文件路径 ///[DllImport("Kernel32.dll")] public static extern Int32 WritePrivateProfileString( string sectionName, string keyName, string value, string fileName); /// /// ini配置文件读取配置 /// /// 段名 /// 键名 /// 当键不存在时的默认值 /// 当前读取到的数据 /// 需要读取的数据大小 /// ini文件路径 ///[DllImport("kernel32.dll")] public static extern Int32 GetPrivateProfileString( string sectionName, string keyName, string defaultValue, StringBuilder returnValue, UInt32 size, string fileName ); #endregion } } 用法:
// 第一步:系统配置 ini文件 IniFileUtil ini类 private IniFileUtil iniFileUtil; //ini文件保存控件状态 iniFileUtil = new IniFileUtil($"{System.Environment.CurrentDirectory}\\系统设置.ini"); //读 ()中分别代表段名,键名,默认值;在上述代码中有解释 bool a = iniFileUtil.ReadBool("Controls_Stae", "cbToken_Checked", false); //写 保存,将写入的数据存入到ini文件中 string valueToken="0";//0 1 代表布尔值 int v = iniFileUtil.Write("Controls_Stae", "cbToken_Checked", valueToken);
ini文件基本写法
[Serial] //段名
ProName=COM3 //键名和值
BaudBate=4800
DataBits=8
Parity=0
StopBits=1
7. GET,POST方法
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using static System.Net.Mime.MediaTypeNames; namespace Http { public class ApiHttp { //接口地址 //private string HttpPath { get; set; } = "http://127.0.0.1:5273"; private static string Token { get; set; } = "123456"; ///
/// get请求方法 /// /// 地址 /// 参数 /// 请求超时时间,以毫秒为单位 ///public static string ApiGet(string path,string param,int timeout) { //path:http://127.0.0.1:5000 //param:id=1&name=张三 //参数+路径:http://127.0.0.1:5000?id=1&name=张三 string pathAndParam = path; if (!string.IsNullOrEmpty(param)) { pathAndParam += "?" + param; } //创建一个HttpWebRequest对象,用来请求后台 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathAndParam); request.Method = "GET"; //请求方式:GET,POST,PUT, DELETE request.Timeout = timeout; //请求超时时间 request.ContentType = "application/json;UTF-8"; //设置类型 request.Headers.Add("token", Token); //请求头 WebResponse response = request.GetResponse(); //相当于后台返回的对象 Stream stream = response.GetResponseStream(); //response流 StreamReader sr = new StreamReader(stream, Encoding.UTF8); string json = sr.ReadToEnd(); //读取接口返回的数据 //释放对象 response.Close(); sr.Close(); stream.Close(); return json; } /// /// post请求方法 /// /// 请求路径 /// 参数 /// 主题内容 /// 请求超时时间,以毫秒位单位 ///public static string ApiPost(string path, string param, string body, int timeout = 5000) { string pathAndParam = path; if (!string.IsNullOrEmpty(param)) { pathAndParam += "?" + param; } //创建一个HttpWebRequest对象,用来请求后台 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathAndParam); request.Method = "POST"; request.Timeout = timeout; request.ContentType = "application/json;UTF-8"; //设置类型; //设置类型 request.Headers.Add("token", Token); //请求头 //把主体内容添加到请求数据中 if (!string.IsNullOrEmpty(body)) { byte[] buffer = Encoding.UTF8.GetBytes(body); request.ContentLength = buffer.Length; //主体内容的字节长度 Stream requestStream = request.GetRequestStream(); //存放请求的数据 requestStream.Write(buffer, 0, buffer.Length); //把主体内容写到流中 } WebResponse response = request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); string json = sr.ReadToEnd(); return json; } public class JsonData { public int Code { get; set; } public string Message { get; set; } //public List > Data { get; set; } //public List Data { get; set; } public T Data { get; set; } } } }