代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StlDemo1
{
internal class Program
{
static void Main(string[] args)
{
string path = "E:\\Information\\File\\stl\\";
string filePath = $"{path}\\222.STL";
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
// 读取文件头(80 字节)
byte[] headerBytes = br.ReadBytes(80);
string header = Encoding.ASCII.GetString(headerBytes);
// 读取三角面片数量(4 字节)
int facetCount = BitConverter.ToInt32(br.ReadBytes(4), 0);
StringBuilder stlContent = new StringBuilder();
stlContent.AppendLine("solid " + header.TrimEnd('\0'));
for (int i = 0; i < facetCount; i++)
{
// 读取法向量(12 字节)
float nx = BitConverter.ToSingle(br.ReadBytes(4), 0);
float ny = BitConverter.ToSingle(br.ReadBytes(4), 0);
float nz = BitConverter.ToSingle(br.ReadBytes(4), 0);
// 读取顶点坐标(36 字节)
float v1x = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v1y = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v1z = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v2x = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v2y = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v2z = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v3x = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v3y = BitConverter.ToSingle(br.ReadBytes(4), 0);
float v3z = BitConverter.ToSingle(br.ReadBytes(4), 0);
// 读取属性字节计数(2 字节)
short attributeByteCount = BitConverter.ToInt16(br.ReadBytes(2), 0);
// 将三角面片信息添加到字符串构建器中
stlContent.AppendLine($" facet normal {nx} {ny} {nz}");
stlContent.AppendLine(" outer loop");
stlContent.AppendLine($" vertex {v1x} {v1y} {v1z}");
stlContent.AppendLine($" vertex {v2x} {v2y} {v2z}");
stlContent.AppendLine($" vertex {v3x} {v3y} {v3z}");
stlContent.AppendLine(" endloop");
stlContent.AppendLine(" endfacet");
}
stlContent.AppendLine("endsolid");
// 输出 STL 文件内容
Console.WriteLine(stlContent.ToString());
// 如果需要将字符串保存到新的文件中
string outputFilePath = $"{path}\\字符串格式.stl";
File.WriteAllText(outputFilePath, stlContent.ToString());
Console.WriteLine("二进制 STL 文件已成功转换为字符串并保存到新的文件中。");
}
}
catch (Exception ex)
{
Console.WriteLine("读取或写入文件时发生错误: " + ex.Message);
}
Console.ReadKey();
}
}
}
end