C#工具集
本人自己写了一些常用的工具集,并封装成了工具类,只需将文件copy,就能使用,非常方便。
目前工具类包含:UDP工具类、串口工具类、TXT文本工具、Chart动态曲线绘制工具,后续还会持续更新一些常用工具…
1、UDP工具类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace CSharpTool
{
class UdpTool
{
private Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private UdpTool()
{
}
public static UdpTool getUdoToolObj()
{
return new UdpTool();
}
public bool SetUdpIpAndPort(String ip,String port)
{
bool res = false;
try
{
socket.Bind(new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));
res = true;
}
catch (Exception e)
{
res = false;
}
return res;
}
public int UdpReceiveBuffer(Byte[] recBuffer)
{
int recDataLen = 0;
EndPoint point = new IPEndPoint(IPAddress.Any, 0);
try
{
recDataLen = socket.ReceiveFrom(recBuffer, ref point);
}
catch (Exception e)
{
recDataLen = 0;
}
return recDataLen;
}
public string UdpReceiveString()
{
Byte[] recBuffer = new byte[1024];
string recDataString = "";
EndPoint point = new IPEndPoint(IPAddress.Any, 0);
try
{
socket.ReceiveFrom(recBuffer, ref point);
recDataString = Encoding.Default.GetString(recBuffer);
}
catch (Exception e)
{
recDataString = "";
}
return recDataString;
}
public int UdpSendByte(String ip, String port, byte[] sendBuffer)
{
int sendDataLen = 0;
try
{
EndPoint point = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
socket.SendTo(sendBuffer, point);
}
catch (Exception e)
{
sendDataLen = 0;
}
return sendDataLen;
}
public int UdpSendString(String ip, String port, string sendString)
{
int sendDataLen = 0;
try
{
EndPoint point = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port));
socket.SendTo(Encoding.Default.GetBytes(sendString), point);
}
catch (Exception e)
{
sendDataLen = 0;
}
return sendDataLen;
}
public void CloseUdp()
{
if (null != socket)
{
socket.Close();
}
}
}
}
2、串口工具类
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpTool
{
class UartTool
{
private SerialPort serialPort = new SerialPort();
private UartTool()
{
}
public static UartTool getUartToolObj()
{
return new UartTool();
}
public string[] getUartPort()
{
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
string[] sSubKeys = keyCom.GetValueNames();
string[] str = new string[sSubKeys.Length];
for (int i = 0; i < sSubKeys.Length; i++)
{
str[i] = (string)keyCom.GetValue(sSubKeys[i]);
}
return str;
}
public void openUart(string portName, int boudRate, int dataBit, int stopBit, int timeout)
{
try
{
serialPort.PortName = portName;
serialPort.BaudRate = boudRate;
serialPort.DataBits = dataBit;
serialPort.StopBits = (StopBits)stopBit;
serialPort.ReadTimeout = timeout;
serialPort.Open();
}
catch (Exception e)
{
throw e;
}
}
public void closeUart()
{
try
{
serialPort.Close();
}
catch (Exception e)
{
throw e;
}
}
public void uartSendString(string sendData, Encoding encodingType)
{
try
{
serialPort.Encoding = encodingType;
serialPort.Write(sendData);
}
catch (Exception e)
{
throw e;
}
}
public void uartSendByteArray(byte[] sendByteArray,int sendStart,int sendLen)
{
try
{
serialPort.Write(sendByteArray, sendStart, sendLen);
}
catch (Exception e)
{
throw e;
}
}
public void uartSendCharArray(char[] sendCharArray, int sendStart, int sendLen)
{
try
{
serialPort.Write(sendCharArray, sendStart, sendLen);
}
catch (Exception e)
{
throw e;
}
}
public int uartReadByteArray(byte[] buffer,Encoding encodingType)
{
int bytes = serialPort.BytesToRead;
int readLen = 0;
try
{
serialPort.Encoding = encodingType;
readLen = serialPort.Read(buffer, 0, bytes);
}
catch (Exception e)
{
readLen = 0;
throw e;
}
return readLen;
}
public String uartReadString(Encoding encodingType)
{
int bytes = serialPort.BytesToRead;
int readLen = 0;
string read = "";
char[] array = new char[10000];
try
{
serialPort.Encoding = encodingType;
readLen = serialPort.Read(array, 0, bytes);
read = new string(array);
}
catch (Exception e)
{
read = "";
throw e;
}
return read;
}
}
}
3、TXT文本工具类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpTool
{
class TxtTool
{
FileStream stream = null;
StreamWriter writer = null;
StreamReader reader = null;
private TxtTool()
{
}
public static TxtTool getTxtToolObj()
{
return new TxtTool();
}
public void TxtWrite(string txtPath, string data)
{
this.reader = null;
if (null == this.writer)
{
stream = new FileStream(txtPath, FileMode.Create);
writer = new StreamWriter(stream);
}
writer.WriteLine(data);
}
public string TxtRead(string txtPath)
{
string str = "";
this.writer = null;
if (null == this.reader)
{
stream = new FileStream(txtPath, FileMode.Open);
reader = new StreamReader(stream);
}
str = reader.ReadToEnd();
return str;
}
public void closeStream()
{
if (null != this.stream)
{
stream.Close();
}
}
public void closeReader()
{
if (null != this.reader)
{
reader.Close();
}
}
public void closeWriter()
{
if (null != this.writer)
{
writer.Close();
}
}
}
}
4、Chart动态曲线绘制工具
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.DataVisualization.Charting;
namespace CSharpTool
{
class ChartTool
{
private DateTime dtTime = DateTime.Now;
private double YMax = 10.0;
private ChartTool()
{
}
public static ChartTool getChartToolObj()
{
return new ChartTool();
}
public void InitChart(Chart chart,String ChartName,String ChartXName,String ChartYName,int LineNum)
{
chart.ChartAreas[0].AxisX.Title = ChartXName;
chart.ChartAreas[0].AxisY.Title = ChartYName;
chart.ChartAreas[0].AxisX.Interval = 1;
chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.NotSet;
chart.ChartAreas[0].AxisY.IntervalType = DateTimeIntervalType.Number;
chart.ChartAreas[0].AxisY.Interval = 0.5;
chart.ChartAreas[0].AxisY.Maximum = 10;
chart.ChartAreas[0].AxisY.Minimum = 0;
chart.ChartAreas[0].AxisY.IsStartedFromZero = false;
for (int i = 0; i < LineNum; i++)
{
chart.Series.Add("曲线" +( i +1));
}
for (int i = 0; i < 60; i++)
{
for (int j= 0; j < LineNum; j++)
{
DataPoint dp = new DataPoint();
dp.SetValueXY(DateTime.Now.AddSeconds(-60 + i).ToString("HH:mm:ss fff"), 0);
chart.Series[j].Points.Add(dp);
}
}
for (int i = 0; i < LineNum; i++)
{
chart.Series[i].IsValueShownAsLabel = false;
chart.Series[i].ChartType = SeriesChartType.Line;
chart.Series[i].BorderDashStyle = ChartDashStyle.Solid;
chart.Series[i].BorderWidth = 3;
chart.Series[i].ToolTip = "#VALX:#VALY";
chart.Series[i].IsVisibleInLegend = true;
}
}
public void DrawChartLine(Chart chart,int LineId,double LineX,double LineY)
{
if (LineY > YMax)
{
chart.ChartAreas[0].AxisY.Maximum = LineY;
YMax = LineY;
}
chart.Series[LineId].Points.RemoveAt(0);
chart.Series[LineId].Points.AddXY(dtTime.AddMilliseconds(LineX).ToString("HH:mm:ss fff"), LineY.ToString("0.00"));
}
}
}
代码亲测可用,完整项目可到本人github仓库下载:
github仓库链接