using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace TeamAAS_VP.Core { public static class Common { /// /// 解析带前导零的 IP 地址字符串 /// /// /// /// public static IPAddress ParseIpWithLeadingZeros(string ipString) { // 分割 IP 地址的四个部分 string[] parts = ipString.Split('.'); if (parts.Length != 4) throw new FormatException("Invalid IP address format."); // 处理每个部分的前导零 for (int i = 0; i < parts.Length; i++) { string part = parts[i]; if (string.IsNullOrEmpty(part)) throw new FormatException("IP part cannot be empty."); // 去除前导零(保留纯 "0" 的情况) if (part.Length > 1 && part.StartsWith("0")) { part = part.TrimStart('0'); // 如果去除后为空,说明原部分全为0,补回一个0 if (string.IsNullOrEmpty(part)) part = "0"; } // 验证数值范围 0-255 if (!int.TryParse(part, out int value) || value < 0 || value > 255) return null; parts[i] = value.ToString(); // 确保无前导零的字符串 } // 重新组合为修正后的 IP 地址 string correctedIp = string.Join(".", parts); return IPAddress.Parse(correctedIp); } /// /// 将DataTable导出到csv文件中 /// /// /// public static void ExportToCsv(System.Data.DataTable dataTable, string filePath) { StringBuilder sb = new StringBuilder(); //添加列名 foreach (System.Data.DataColumn column in dataTable.Columns) { sb.Append(column.ColumnName + ","); } sb.AppendLine(); //添加数据 foreach (System.Data.DataRow row in dataTable.Rows) { foreach (var item in row.ItemArray) { sb.Append(item.ToString() + ","); } sb.AppendLine(); } System.IO.File.WriteAllText(filePath, sb.ToString()); } /// /// 计算两点之间的角度(弧度) /// /// /// /// public static double CalculateAngleBetweenPoints(PointF p1, PointF p2) { double deltaY = p2.Y - p1.Y; double deltaX = p2.X - p1.X; // 使用 Atan2 计算角度(弧度) // Atan2 自动处理四个象限,返回值在 -π 到 π 之间 double angleRad = Math.Atan2(deltaY, deltaX); return angleRad; } /// /// 计算两点之间的角度(度) /// /// /// /// public static double CalculateAngleBetweenPointsDegrees(PointF p1, PointF p2) { double angleRad = CalculateAngleBetweenPoints(p1, p2); return angleRad * (180.0 / Math.PI); } /// /// 使用 Math 类计算两点距离 /// /// /// /// /// /// public static double CalculateDistance2D(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; return Math.Sqrt(dx * dx + dy * dy); } } }