Files
wg_cpso/CuttingForce2/ToolPositionList.cs
2026-03-25 18:20:24 +08:00

85 lines
2.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text;
namespace ToolPathParser
{
internal class ToolPositionList
{
public List<ToolPosition> Process()
{
var exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string inputPath = Path.Join(exeDirectory, "toolposition.txt");
List<ToolPosition> result = ToolPathProcessor.ProcessToolPath(
inputPath,
totalPointsPerLayer: 50,
radialDepth: 1.0,
zOrigin: 0.0);
return result;
}
// 将对象列表写入CSV文件
public void WriteListToCsv<T>(List<T> dataList, string filePath)
{
if (dataList == null || dataList.Count == 0)
{
throw new ArgumentException("数据列表不能为空", nameof(dataList));
}
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException("文件路径不能为空", nameof(filePath));
}
// 创建StringBuilder提高拼接效率
StringBuilder csvContent = new StringBuilder();
var properties = typeof(T).GetProperties();
// 第一步写入CSV表头使用对象的属性名作为列名
List<string> headerNames = new List<string>();
foreach (var prop in properties)
{
headerNames.Add(EscapeCsvValue(prop.Name));
}
csvContent.AppendLine(string.Join(",", headerNames));
// 第二步:写入数据行
foreach (var item in dataList)
{
List<string> rowValues = new List<string>();
foreach (var prop in properties)
{
// 获取属性值并处理空值
object value = prop.GetValue(item) ?? string.Empty;
// 转义CSV特殊字符
rowValues.Add(EscapeCsvValue(value.ToString()));
}
csvContent.AppendLine(string.Join(",", rowValues));
}
// 第三步将内容写入文件使用UTF-8编码避免中文乱码
File.WriteAllText(filePath, csvContent.ToString(), Encoding.UTF8);
}
// 转义CSV格式的特殊字符逗号、引号、换行符
private static string EscapeCsvValue(string? value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
// 如果包含逗号、双引号、换行/回车,需要用双引号包裹
if (value.Contains(",") || value.Contains("\"") || value.Contains("\n") || value.Contains("\r"))
{
// 双引号需要替换为两个双引号CSV转义规则
return $"\"{value.Replace("\"", "\"\"")}\"";
}
return value;
}
}
}