CNC机床C#坐标记录宏报CS1513/CS1022错误求排查
解决C#宏的CS1513和CS1022编译错误
问题背景
通过CNC机床摄像头展示待加工零件视图,手动移动机床时记录感兴趣点的X、Y坐标(从Xmachpos和Ymachpos内部寄存器读取)并写入CSV文件。运行提供的C#宏时,出现CS1513(缺少“}”)和CS1022(命名空间EOF)编译错误,无法定位问题。
原始代码
using System; using System.IO; using System.Windows.Forms; class Program { static void Main(string[] args) { string filePath = @"C:\dxf.txt"; int Xpos, Ypos; //Check if file exists and create it if not if (!File.Exists(filePath)) { File.Create(filePath).Close(); } //Write Xpos and Ypos values to file and prompt user to enter more values do { Xpos = exec.GetXmachpos(); Ypos = exec.GetYmachpos(); using (StreamWriter writer = File.AppendText(filePath)) { writer.WriteLine(Xpos.ToString() + "," + Ypos.ToString()); } } while (PromptUser()); MessageBox.Show("Values written to file. Click OK to exit."); } static bool PromptUser() { DialogResult result = MessageBox.Show("Do you want to enter more values?", "Enter Values", MessageBoxButtons.YesNo, MessageBoxIcon.Question); return (result == DialogResult.Yes); } }
错误原因分析
从代码结构看,括号匹配看似完整,但以下两点可能导致编译错误:
- 缺少命名空间包裹:部分CNC机床的宏环境强制要求代码必须包含在命名空间内,否则编译器会判定代码结构不完整,触发
CS1022错误。 - 不可见特殊字符:复制粘贴代码时可能带入全角符号、非标准换行符等不可见字符,导致编译器解析失败,触发
CS1513错误。
修复后的代码
using System; using System.IO; using System.Windows.Forms; namespace CNC_Position_Recorder { class Program { static void Main(string[] args) { string filePath = @"C:\dxf.txt"; int Xpos, Ypos; // 检查文件是否存在,不存在则创建 if (!File.Exists(filePath)) { using (File.Create(filePath)) {} // 使用using自动释放文件资源,避免占用 } // 写入坐标并提示用户是否继续 do { Xpos = exec.GetXmachpos(); Ypos = exec.GetYmachpos(); using (StreamWriter writer = File.AppendText(filePath)) { writer.WriteLine($"{Xpos},{Ypos}"); // 字符串插值简化拼接 } } while (PromptUser()); MessageBox.Show("坐标已写入文件,点击OK退出。"); } static bool PromptUser() { DialogResult result = MessageBox.Show("是否继续记录坐标?", "坐标记录", MessageBoxButtons.YesNo, MessageBoxIcon.Question); return result == DialogResult.Yes; } } }
额外注意事项
- 确认
exec对象在当前宏环境中已正确初始化,否则会出现运行时错误。 - 如果机床返回的坐标为浮点数,将
int Xpos, Ypos;改为double Xpos, Ypos;,并对应调整寄存器读取方法的返回类型。 - 若写入
C:\目录权限不足,可将文件路径改为用户文档目录:Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\dxf.txt"。
内容的提问来源于stack exchange,提问作者David Childs
相关产品推荐
相关产品推荐

